介绍
本篇内容介绍了“Java文件读写IO/NIO及性能的比较“的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
文件读写有以下几种常用的方法
1,字节读写(InputStream/OutputStream)
2,字符读取(FileReader/FileWriter)
3,行读取(BufferedReader/BufferedWriter)
代码(以读取为例):
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream;/* *, ,* & lt; b>文件读取类& lt;/b> & lt; br /祝辞, ,* 1,按字节读取文件内容& lt; br /祝辞, ,* 2,按字符读取文件内容& lt; br /祝辞, ,* 3,按行读取文件内容& lt; br /祝辞, ,* @author qin_xijuan *大敌; ,*/public class  FileOperate { private static  final String FILE_PATH =,“d:/工作/,List of Beautiful Music.txt";/* *, ,,*,以字节为单位读取文件内容, ,,*,@param filePath:需要读取的文件路径, ,,*/public static  void readFileBybyte (String filePath), { File File =, new 文件(filePath);//,InputStream:此抽象类是表示字节输入流的所有类的超类只 InputStream ins =, null ; 尝试{//,FileInputStream:从文件系统中的某个文件中获得输入字节又是; 时间=ins new FileInputStream(文件); int temp ;//,read():从输入流中读取数据的下一个字节又是; 而((=temp ins.read ()) !=1) { System.out.write(临时); } } 抓住(Exception e) { e.getStackTrace (); } 最后{ if (ins !=, null) { 尝试{ ins.close (); } 抓住(IOException e) { e.getStackTrace (); } } } }/* *, ,,*,以字符为单位读取文件内容, ,,*,@param filePath ,,*/public static  void readFileByCharacter (String filePath) { File File =, new 文件(filePath);//,FileReader:用来读取字符文件的便捷类只 FileReader reader =,空; 尝试{ 时间=reader new FileReader(文件); int temp ; 而((=temp reader.read ()), !=, 1) { if (((char),临时),!=,& # 39;\ " # 39;),{ System.out.print ((char),临时); } } } 抓住(IOException e) { e.getStackTrace (); } 最后{ if (reader !=, null) { try { reader.close (); } catch (IOException e), { e.printStackTrace (); } } } }/* *, ,,*,以行为单位读取文件内容, ,,*,@param filePath ,,*/public static  void readFileByLine (String filePath) { File File =, new 文件(filePath);//,BufferedReader:从字符输入流中读取文本,缓冲各个字符,从而实现字符,数组和行的高效读取只 BufferedReader buf =,空; 尝试{//,FileReader:用来读取字符文件的便捷类只 时间=buf new BufferedReader (new FileReader(文件);=//,buf new BufferedReader (new InputStreamReader (new FileInputStream(文件))),, String temp =, null ; while ((temp =, buf.readLine ()), !=, null ) { System.out.println(临时); } } 抓住(Exception e) { e.getStackTrace (); } 最后{ 如果(buf !=, null) { 尝试{ buf.close (); } catch (IOException e), { e.getStackTrace (); } } } } public static  void 主要(String 参数[]),{ readFileBybyte (FILE_PATH); readFileByCharacter (FILE_PATH); readFileByLine (FILE_PATH); } }
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -分割线- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
再经过两位同行的提点下,我对之前写的文件做了点修改,并通过读写一个1.2米的文本文件来测试各方法的性能。从多次测试结果来看,行读写却是是Java。nio更有效率。