java写文件方法之比较
import java.io.BufferedOutputStream;
创新互联主营邹城网站建设的网络公司,主营网站建设方案,重庆App定制开发,邹城h5小程序开发搭建,邹城网站营销推广欢迎邹城等地区企业咨询
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* 测试各种写文件的方法性能。
*
* @author 老紫竹 JAVA世纪网(java2000.net)
*
*/
public class T {
public static void main(String[] args) {
FileOutputStream out = null;
FileOutputStream outSTr = null;
BufferedOutputStream Buff = null;
FileWriter fw = null;
int count = 1000000;// 写文件行数
try {
byte[] bs = "测试java 文件操作/r/n".getBytes();
out = new FileOutputStream(new File("C:/add.txt"));
long begin = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
out.write(bs);
}
out.close();
long end = System.currentTimeMillis();
System.out.println("FileOutputStream执行耗时:" + (end - begin) + " 豪秒");
outSTr = new FileOutputStream(new File("C:/add0.txt"));
Buff = new BufferedOutputStream(outSTr);
long begin0 = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
Buff.write(bs);
}
Buff.flush();
Buff.close();
long end0 = System.currentTimeMillis();
System.out.println("BufferedOutputStream执行耗时:" + (end0 - begin0) + " 豪秒");
fw = new FileWriter("C:/add2.txt");
long begin3 = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
fw.write("测试java 文件操作/r/n");
}
fw.flush();
fw.close();
long end3 = System.currentTimeMillis();
System.out.println("FileWriter执行耗时:" + (end3 - begin3) + " 豪秒");
long begin4 = System.currentTimeMillis();
String path = "C:/add3.txt";
ByteBuffer bb = ByteBuffer.wrap(bs);
FileChannel out2 = new FileOutputStream(path).getChannel();
for (int i = 0; i < count; i++) {
out2.write(bb);
bb.rewind();
}
out2.close();
long end4 = System.currentTimeMillis();
System.out.println("FileChannel执行耗时:" + (end4 - begin4) + " 豪秒");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fw.close();
Buff.close();
outSTr.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
在我的笔记本上,运行结果如下
FileOutputStream执行耗时:4891 豪秒
BufferedOutputStream执行耗时:78 豪秒
FileWriter执行耗时:438 豪秒
FileChannel执行耗时:2812 豪秒
当然最终生成的文件都是正确的
总结:
BufferedOutputStream 由于有缓冲,性能明显好
FileOutputStream 性能最差,因为其每次都写入字节。
FileWriter 性能很一般
FileChannel使用了nio,但如果没有缓冲,必能太指望性能了
本文题目:java写文件方法之比较
链接分享:http://ybzwz.com/article/jesdch.html