说明:
1.d:/iotest/1.txt文件是一个纯文本文件,大小为25.4M;
2.execute1方法不使用缓冲区,execute2方法使用缓冲区;
3.execute1方法和execute2方法分别循环10次;
结果:
execute1方法循环10次所需时间4.059s
execute2方法循环10次所需时间5.730s
上代码:
package io;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import org.junit.Test;
public class Reader_Writer_Test {
@Test
public void testExecute() {
for (int i = 0; i <10; i++) {
execute1();
//execute2();
}
}
/**
* 简单描述:不使用缓冲区BufferedReader,BufferedWriter
* <p>
*/
private static void execute1() {
Reader fileReader = null;
Writer fileWriter = null;
try {
fileReader = new FileReader(“d:/iotest/1.txt”);
// fileReader = new FileReader(new File(“d:/iotest/reader.txt”));
fileWriter = new FileWriter(“d:/iotest/111.txt”);
char[] cbuf = new char[1024*1024];
int lenth = 0;
while ((lenth = fileReader.read(cbuf)) != -1) {
fileWriter.write(cbuf, 0, lenth);
fileWriter.flush();
}
fileWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != fileReader) {
fileReader.close();
}
if (null != fileWriter) {
fileWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 简单描述:使用缓冲区BufferedReader,BufferedWriter
* <p>
*/
private static void execute2() {
BufferedReader bufReader = null;
BufferedWriter bufWriter = null;
try {
bufReader = new BufferedReader(new FileReader(“d:/iotest/1.txt”));
bufWriter = new BufferedWriter(new FileWriter(“d:/iotest/222.txt”));
String line = null;
while ((line = bufReader.readLine()) != null) {
bufWriter.write(line);
bufWriter.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != bufReader) {
bufReader.close();
}
if (null != bufWriter) {
bufWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}