1指定每次读2个字节
FileInputStream fis = new FileInputStream("c.txt");
int length;
byte[] bytes=new byte[2];
while ((length=fis.read(bytes))!=-1){
System.out.println("bytes = " + new String(bytes,0,length));
}
fis.close();
日志:
bytes = df
bytes = 6y
bytes = y6
bytes = 56
2 读写文件
System.out.println("start = " + new Date().toLocaleString());
FileInputStream fis = new FileInputStream("c.txt");
FileOutputStream fileOutputStream = new FileOutputStream("c1.txt");
int length;
byte[] bytes=new byte[2];
while ((length=fis.read(bytes))!=-1){
System.out.println("bytes = " + new String(bytes,0,length));
System.out.println("toLocaleString = " + new Date().toLocaleString());
fileOutputStream.write(bytes,0,length);
}
fis.close();
fileOutputStream.close();
System.out.println("end = " + new Date().toLocaleString());
700M文件
start = 2021年7月4日上午10:55:44
end = 2021年7月4日上午10:55:49
3缓冲流读写文件(默认自建缓冲区)
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("c.txt"));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("c2.txt"));
int length;
while ((length=bufferedInputStream.read())!=-1){
System.out.println("length = " + length);
bufferedOutputStream.write(length);
}
bufferedInputStream.close();
bufferedOutputStream.close();
700M文件
start = 2021年7月4日上午10:50:29
end = 2021年7月4日上午10:50:51
4缓冲流+数组读写文件
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("c.txt"));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("c3.txt"));
int length;
byte[] bytes = new byte[1024];
while ((length=bufferedInputStream.read(bytes))!=-1){
System.out.println("length = " + new String(bytes,0,length));
bufferedOutputStream.write(bytes,0,length);
}
bufferedInputStream.close();
bufferedOutputStream.close();
700M文件
1S
总结:
当缓存数组都设为1024时,读写700M文件基础流FileInputStream耗时4秒,高级缓存流BufferInputStream耗时1秒;然而byte数组设为10*1024时,基础流和缓存流耗时均为1秒。可见读写文件的效率主要取决于数组byte设定的大小,而与流的高级与否关系不大。