将1~100000整数写入(读取)out.txt文件中,记录不同写入方式的运行时间
一、无缓冲写
public class Main {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("D:\\out.txt");
long start = System.currentTimeMillis();
for (int i = 0; i < 1e6; ++i) {
fos.write(i);
}
fos.close();
long end = System.currentTimeMillis();
System.out.println("time = " + (end - start) + "ms");
}
}
用时:2053ms
二、有缓冲写
BufferedOutputStream提供了一个byte数组作为缓冲区,默认大小为8KB。缓冲区写满后才会真正地写入磁盘。
public class Main {
public static void main(String[] args) throws Exception {
BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream("D:\\out.txt"));
long start = System.currentTimeMillis();
for (int i = 1; i <= 1e6; ++i) {
fos.write(i);
}
fos.flush();
fos.close();
long end = System.currentTimeMillis();
System.out.println("time = " + (end - start) + "ms");
}
}
用时:53ms
在创建BufferedOutputStream对象时也可以指定缓冲区大小,当指定为1时,又变为了无缓冲写。
public class Main {
public static void main(String[] args) throws Exception {
BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream("D:\\out.txt"), 1);
long start = System.currentTimeMillis();
for (int i = 1; i <= 1e6; ++i) {
fos.write(i);
}
fos.flush();
fos.close();
long end = System.currentTimeMillis();
System.out.println("time = " + (end - start) + "ms");
}
}
用时:2117ms
三、无缓冲读
public class Main {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("D:\\out.txt");
int b = 0;
long start = System.currentTimeMillis();
while ((b = fis.read()) != -1);
fis.close();
long end = System.currentTimeMillis();
System.out.println("time = " + (end - start) + "ms");
}
}
用时:1757ms
四、有缓冲读
public class Main {
public static void main(String[] args) throws Exception {
BufferedInputStream fis = new BufferedInputStream(new FileInputStream("D:\\out.txt"));
int b = 0;
long start = System.currentTimeMillis();
while ((b = fis.read()) != -1);
fis.close();
long end = System.currentTimeMillis();
System.out.println("time = " + (end - start) + "ms");
}
}
用时:19ms