- 最近线上经常出现多文件下载,JVM内存爆了的情况,借此复习一下IO读写数据,文章就常规IO流读写数据、缓冲IO流读写数据、NIO读写数据做测试。
- 结果:
普通IO流效果最差;
缓冲流使用默认size即8192 和 NIO 8192Buffer的速度接近;修改缓冲流size为16384 、 NIO Buffer为16384,速度仍然接近;但是NIO相对来说占有优势。(耗时单位为mills,值为20次结果取均值,读取文件大小102MB)
![在这里插入图片描述](https://img-blog.csdnimg.cn/3e815b63b370403887f1e060506fe640.png)
- 代码
class Test{
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream("D:\\vedio.ev4");
FileOutputStream fileOutputStream = new FileOutputStream("D:\\testA\\vedio.ev4");
long beginMethodA = System.currentTimeMillis();
methodA();
long endMethodA = System.currentTimeMillis();
System.out.println( "methodA count " + (endMethodA-beginMethodA));
long beginMethodB = System.currentTimeMillis();
methodB();
long endMethodB = System.currentTimeMillis();
System.out.println( "methodB count " + (endMethodB-beginMethodB));
long beginMethodC = System.currentTimeMillis();
methodC();
long endMethodC = System.currentTimeMillis();
System.out.println( "methodB count " + (endMethodC-beginMethodC));
}
public static void methodA() throws IOException {
FileInputStream fileInputStream = new FileInputStream("D:\\vedio.ev4");
FileOutputStream fileOutputStream = new FileOutputStream("D:\\testA\\vedio.ev4");
byte[] bytes = new byte[1024];
int len;
try {
while( (len = fileInputStream.read(bytes)) != -1 ){
fileOutputStream.write(bytes,0,len);
}
}catch (Exception e){
System.out.println("exception");
}finally {
if(fileInputStream != null){
fileInputStream.close();
}
if(fileOutputStream != null){
fileOutputStream.close();
}
}
}
public static void methodB() throws IOException {
FileInputStream fileInputStream = new FileInputStream("D:\\vedio.ev4");
BufferedInputStream bis = new BufferedInputStream(fileInputStream);
FileOutputStream fileOutputStream = new FileOutputStream("D:\\testA\\vedio2.ev4");
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
byte[] bytes = new byte[1024];
int len;
try {
while( (len = bis.read(bytes)) != -1 ){
bos.write(bytes,0,len);
}
}catch (Exception e){
System.out.println("exception");
}finally {
if(bis != null){
bis.close();
}
if(bos != null){
bos.close();
}
}
}
public static void methodC() throws IOException {
RandomAccessFile randomAccessFile = new RandomAccessFile("D:\\vedio.ev4","rw");
RandomAccessFile randomAccessFile1 = new RandomAccessFile("D:\\testA\\vedio3.ev4","rw");
FileChannel readChannel = randomAccessFile.getChannel();
FileChannel writeChannel = randomAccessFile1.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(8192);
try{
int byteRead= readChannel.read(byteBuffer);
while (byteRead!=-1){
byteBuffer.flip();
while (byteBuffer.hasRemaining()){
writeChannel.write(byteBuffer);
}
byteBuffer.compact();
byteRead= readChannel.read(byteBuffer);
}
}catch(Exception e ){
e.printStackTrace();
}finally{
if(readChannel != null){
readChannel.close();
}
if( writeChannel != null){
writeChannel.close();
}
randomAccessFile.close();
randomAccessFile1.close();
}
}
}