目录
0、写在前面
本节为软件构造系列Chapter8中的I/O性能部分的补充。
1、I/O
Java的I/O操作比较多,具体可以查询Java文档,Chrome中使用Ctrl+F查询io或nio即可。
这里主要介绍四种比较基本I/O方式,每种读写大致可以分为两种,按行读取和按字节读取,整体来说,大同小异。在此实现最基本的操作。
对于下面涉及的文件地址及File对象,在下面定义:
/* in file */
String filePathIn = "file.txt";
File fileIn = new File(filePath);
/* out file */
String filePathOut = "Out.txt";
File fileOut = new File(filePathOut);
1.1、BufferedReader/Writer
使用缓存区的读写方式。
1.1.1、BufferedReader
这里把brCh的大小设置为file.length()
,一次性把文件加载到缓存中,之后可以进行解析等操作;也可以设置为特定的值(eg. 1024)等,分次加载。
/* new FileReader(fileIn)读写器 */
BufferedReader brIn = new BufferedReader(new FileReader(fileIn));
/* 文件大小 */
char[] brCh = new char[(int) fileIn.length()];
/* 读取进入brCh */
brIn.read(brCh);
brIn.close();
1.1.2、BufferedWriter
BufferedWriter bwOut = new BufferedWriter(new FileWriter(fileOut));
/* 将之前读取的brCh数组写入内存 */
bwOut.write(brCh);
bwOut.close();
1.2、nio Files
新IO操作,有很多改进,效率较高,操作较简单。
1.2.1、read
/* 按字节读取 */
byte[] nioBy = Files.readAllBytes(Paths.get(filePathIn));
/* 一次性读取所有行,可以使用for-each遍历 */
//String[] lines = Files.readAllLines(Paths.get(filePathIn));
1.2.2、write
/* 将之前读取的nioBy字节数组写入内存 */
Files.write(Paths.get(filePathOut), nioBy);
1.3、Scanner/PrintWriter
1.3.1、Scanner
/* 创建Scanner读取 */
Scanner scIn = new Scanner(fileIn);
/* 使用StringBuffer保存,避免生成太多临时变量 */
StringBuffer scStr = new StringBuffer();
String scLine;
/* 按行读取 */
while (scIn.hasNextLine()) {
scLine = scIn.nextLine();
scStr.append(scLine + "\n");
}
scIn.close();
1.3.2、PrintWriter
/* 写入器 */
PrintWriter pwOut = new PrintWriter(fileOut);
/* 将之前读取保存的StringBuffer转为String类型,然后写入文件 */
pwOut.write(scStr.toString());
pwOut.close();
1.4、Stream
使用文件流操作。
1.4.1、InputStream
InputStream disIn = new FileInputStream(fileIn);
/* 保存的字节数组 */
byte dosB[] = new byte[(int) fileIn.length()];
/* 一次加载进缓存 */
disIn.read(dosB);
disIn.close();
1.4.2、OutputStream
OutputStream dosOut = new FileOutputStream(fileOut);
/* 将读取的字节数组写入文件 */
dosOut.write(dosB);
dosOut.close();
2、性能对比
参考:
javadoc