下面介绍两种读写文件的对比,
1:InputStream/OutputStream操作byte[]
2:Channel操作buffer
(Reader /Writer读写文件的方式就不比较了,其性能比上面两种方式差很多)
先来说说两种方式对比后的结果:总体来说第一种方式对比第二种方式有如下的缺点
1:速度慢,下面代码运行结果表明 Channel操作buffer速度快于InputStream/OutputStream操作byte[]
下面是我的测试代码:从F盘中读取spittr.war文件,然后重命名写入F盘。输出所需要的时间。
public class Test {
public static void main(String[] args) throws IOException{
byStream();//InputStream/OutputStream操作byte[]
byChannel(); //Channel操作buffer
}
static void byChannel() throws IOException {
File file = new File("F:"+File.separator+"spittr.war");
FileInputStream fins = new FileInputStream(file);
FileChannel fc = fins.getChannel();
File file2 = new File("F:"+File.separator+"Channel.war");
FileOutputStream fos = new FileOutputStream(file2);
FileChannel foc = fos.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024*1024);
int temp = 0;
long start = System.currentTimeMillis();
while ((temp = fc.read(buffer) )!=-1) {
buffer.flip();
foc.write(buffer);
buffer.clear();
}
System.out.println("byChannel:"+(System.currentTimeMillis() - start));
fc.close();
fins.close();
foc.close();
fos.close();
}
static void byStream() throws IOException{
File file = new File("F:"+File.separator+"spittr.war");
FileInputStream fins = new FileInputStream(file);
File file2 = new File("F:"+File.separator+"stream.war");
FileOutputStream fos = new FileOutputStream(file2);
int temp = 0;
long start = System.currentTimeMillis();
byte[] buffer = new byte[1024*1024];
while ((temp = fins.read(buffer) )!=-1) {
fos.write(buffer,0,temp);
}
System.out.println("byStream:"+(System.currentTimeMillis() - start));
fins.close();
fos.close();
}
}
输出结果:
第一次运行:
byStream:40
byChannel:30
第二次运行:
byStream:46
byChannel:27
第三次运行:
byStream:44
byChannel:28
上面的输出结果印证了第二条结果。