2022年java文件读写代码 .pdf
1、按字 节读 取文件内容2、按字符 读取文件内容3、按行 读取文件内容4、随机 读取文件内容publicclass ReadFromFile /*以字 节为单 位读取文件,常用于读二进制文件,如 图片、声音、影像等文件。*/publicstaticvoid readFileByBytes(String fileName)File file=new File(fileName);InputStream in=null;try System.out.println(以字 节为单 位读取文件内容,一次读一个字 节:);/一次 读一个字 节 in=new FileInputStream(file);int tempbyte;while(tempbyte=in.read()!=-1)System.out.write(tempbyte);in.close();catch(IOException e)e.printStackTrace();return;try System.out.println(以字 节为单 位读取文件内容,一次读多个字 节:);/一次 读多个字 节byte tempbytes=newbyte100;int byteread=0;in=new FileInputStream(fileName);ReadFromFile.showAvailableBytes(in);/读入多个字 节到字节数组中,byteread为一次 读入的字 节数while(byteread=in.read(tempbytes)!=-1)System.out.write(tempbytes,0,byteread);名师资料总结-精品资料欢迎下载-名师精心整理-第 1 页,共 6 页 -catch(Exception e1)e1.printStackTrace();finally if(in!=null)try in.close();catch(IOException e1)/*以字符 为单位读取文件,常用于读文本,数字等 类型的文件 */publicstaticvoid readFileByChars(String fileName)File file=new File(fileName);Reader reader=null;try System.out.println(以字符 为单 位读取文件内容,一次读一个字 节:);/一次 读一个字符 reader=new InputStreamReader(new FileInputStream(file);int tempchar;while(tempchar=reader.read()!=-1)/对于 windows下,¥r¥n 这两个字符在一起 时,表示一个 换行。/但如果 这两个字符分 开显 示时,会 换两次行。/因此,屏蔽掉 r,或者屏蔽 n。否 则,将会多出很多空行。if(char)tempchar)!=¥r)System.out.print(char)tempchar);reader.close();catch(Exception e)e.printStackTrace();try 名师资料总结-精品资料欢迎下载-名师精心整理-第 2 页,共 6 页 -System.out.println(以字符 为单 位读取文件内容,一次读多个字 节:);/一次 读多个字符char tempchars=newchar 30;int charread=0;reader=new InputStreamReader(new FileInputStream(fileName);/读入多个字符到字符数组中,charread为一次 读取字符数while(charread=reader.read(tempchars)!=-1)/同样屏蔽掉¥r 不显示if(charread=tempchars.length)&(tempcharstempchars.length-1!=¥r)System.out.print(tempchars);else for (int i=0;i 4)?4:0;/将读文件的 开始位置移到beginIndex位置。randomFile.seek(beginIndex);byte bytes=new byte10;int byteread=0;/一次 读 10 个字 节,如果文件内容不足10 个字 节,则读 剩下的字 节。/将一次 读取的字 节数赋给 byteread while(byteread=randomFile.read(bytes)!=-1)System.out.write(bytes,0,byteread);catch(IOException e)e.printStackTrace();finally if(randomFile!=null)try randomFile.close();catch(IOException e1)/*显示输入流中 还剩的字 节数 */privatestaticvoid showAvailableBytes(InputStream in)try System.out.println(当前字 节输 入流中的字 节数为:+in.available();catch(IOException e)e.printStackTrace();名师资料总结-精品资料欢迎下载-名师精心整理-第 5 页,共 6 页 -publicstaticvoid main(String args)String fileName=C:/temp/newTemp.txt;ReadFromFile.readFileByBytes(fileName);ReadFromFile.readFileByChars(fileName);ReadFromFile.readFileByLines(fileName);ReadFromFile.readFileByRandomAccess(fileName);名师资料总结-精品资料欢迎下载-名师精心整理-第 6 页,共 6 页 -