System.out.println("Test NewBufferedWriter begin.");
bufferedWriter.write("\n");
for (int lineNum = startlineNum; lineNum < maxlineNum; lineNum *= Multiplying) {
begin = System.currentTimeMillis();
testNewBufferedWriter(lineNum);
end = System.currentTimeMillis();
long timeElapse_NewBufferedWriter = end - begin;
bufferedWriter.write(String.valueOf(timeElapse_NewBufferedWriter)+"\t");
}
System.out.println("Test NewOutputStream end.\n");
bufferedWriter.close();
}
/************************** I/O *****************************/
//面向字节
public static void testFileOutputStream (int lineNum) throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream(new File("./testFileOutputStream.txt"));
while (--lineNum > 0) {
fileOutputStream.write("写入文件Data\n".getBytes());
}
fileOutputStream.close();
}
public static void testBufferedOutputStream (int lineNum) throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream(new File("./testBufferedOutputStream.txt"));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
while (--lineNum > 0) {
bufferedOutputStream.write("写入文件Data\n".getBytes());
}
bufferedOutputStream.close();
}
//面向字符
public static void testFileWriter (int lineNum) throws IOException {
FileWriter fileWriter = new FileWriter("./testFileWriter.txt");
while (--lineNum > 0) {
fileWriter.write("写入文件Data\n");
}
fileWriter.close();
}
public static void testBufferedWriter (int lineNum) throws IOException {
FileWriter fileWriter = new FileWriter("./testBufferedWriter.txt");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
while (--lineNum > 0) {
bufferedWriter.write("写入文件Data\n");
}
bufferedWriter.close();
}
/************************** NIO ****************************/
public static void testNewOutputStream (int lineNum) throws IOException {
OutputStream outputStream = Files.newOutputStream(Paths.get("./testNewOutputStream.txt"));
while (--lineNum > 0) {
outputStream.write("写入文件Data\n".getBytes());
}
outputStream.close();
}
public static void testNewBufferedWriter (int lineNum) throws IOException {
BufferedWriter newBufferedReader = Files.newBufferedWriter(Paths.get("./testNewBufferedWriter.txt"));
while (--lineNum > 0) {
newBufferedReader.write("写入文件Data\n");
}
newBufferedReader.close();
}
public static void main (String[] args) throws IOException {
//多次测试时可清空result.txt文件
FileWriter fileWriter = new FileWriter("./Result.txt");
testDriver();
}
}
从上图可以看出,写入行数超过20W以上时,FileOutputStream和NewOutputStream耗费时间远远超出其他4个类。为了清晰,让我们放大其他4个类的图:
可以看出,这4个类中,BufferWriter和NewBufferedWriter所耗费时间更少,但总体差别不是很大。
让我们再来看看,写入26W行数据以下时的情况:
可以看出,在数据量较小的情况下,这4个类所耗费时间的差异并不是很大,在更小的数据量下,它们的效率几乎没有差别。
后记从以上分析可知(注意横坐标写入行数是指数级增加的),各个类的时间复杂度大致为O(1/kn),其中不同的类的k不同,导致了最终巨大的差异。
这里只给出了测试结果,并未分析其底层实现原理,欢迎评论区留言。
另外,我没有在其他机器测试,有兴趣的小伙伴可以将自己的测试结果发出来,共同进步^_^
附件本次测试数据结果(若看不清,可以下载到本地看)