java的BIO与NIO还有SSD

本文分三种情况来传数据:BIO,加buf的BIO, NIO

先说下SSD的情况,使用BIO就可以了,域局网可达最高速度10MB/s。如下图:


没有SSD的情况,我们来优化代码。

先试下BIO,速度2.xMB/s,如下图:

如果我们在Bio基础加上Buffer,可达到3.xMB/s.如下图:

最后我尝试了一下NIO,速度居然只有1.xMB/s.可能是我写法不对,我贴下代码:

private void basicIo(InputStream inStream,OutputStream outs) throws IOException {
	// 循环取出流中的数据
	byte[] b = new byte[512];
	int len;
	long n=0;
	while ((len = inStream.read(b)) > 0){
		n+=len;
		System.out.println("write "+len+" down:"+n);
		outs.write(b, 0, len);
		/*if(n%1000==0){
			outs.flush();
		}*/
	}
}
private void bufferIo(InputStream inStream,OutputStream outs) throws IOException {
	BufferedInputStream bis=new BufferedInputStream(inStream);
	BufferedOutputStream bos=new BufferedOutputStream(outs);
	try {
	// 循环取出流中的数据
	int tmpSize=1024*4;	
	byte[] b = new byte[tmpSize];
	int len;
	long n=0;
	while ((len = bis.read(b)) > 0){
		n+=len;
		System.out.println("write "+len+" down:"+n/1024/1024+"mb");
		bos.write(b);
	}
	}finally {
		
		if(bis!=null) {
			try{bis.close();}catch(Exception e) {
				log.error(e.getMessage(),e);
			};
		}
		if(bos!=null) {
			try{bos.close();}catch(Exception e) {
				log.error(e.getMessage(),e);
			};
		}
	}
	
}

private void bufferNio(FileInputStream fis,OutputStream outs) throws IOException {
	FileChannel fileChannel=fis.getChannel();
	BufferedOutputStream bos=new BufferedOutputStream(outs);
	try {
		// 循环取出流中的数据
		int tmpSize=1024*4;
		ByteBuffer buf = ByteBuffer.allocate(tmpSize);
        int bytesRead = fileChannel.read(buf);
        
        while(bytesRead != -1){
        	
            buf.flip();
            while(buf.hasRemaining()){
            	bos.write(buf.get());
            }
            buf.compact();
            
            bytesRead = fileChannel.read(buf);
        }
    
	
	}finally {
		
		if(fileChannel!=null) {
			try{fileChannel.close();}catch(Exception e) {
				log.error(e.getMessage(),e);
			};
		}
		if(bos!=null) {
			try{bos.close();}catch(Exception e) {
				log.error(e.getMessage(),e);
			};
		}
	}
	
}

那么结论出来了,有SSD的情况,代码都不是问题。没有,就用buffer bio吧。

文/程忠 浏览次数:0次   2020-11-30 11:49:01

相关阅读


评论:
点击刷新

↓ 广告开始-头部带绿为生活 ↓
↑ 广告结束-尾部支持多点击 ↑