java IO/NIO 下载上传的笔记

传统古老的上传下载方式大概主要是用BufferedStream来提高上传下载的速度,因为使用它要比其他的Stream方式要快一些。

/**
	 * download file use buffered stream, this is an old version
	 * @param filePath
	 * @throws IOException 
	 */
	public static void downLoadBySimple(String filePath,String savePath){
		BufferedReader inputStream=null;
		BufferedWriter outputStream=null;
		try{
			inputStream=new BufferedReader(new FileReader(filePath));
			outputStream=new BufferedWriter(new FileWriter(savePath));
			
			int c=0;
			
			while((c=inputStream.read())!=-1){
				outputStream.write(c);
			}
		}catch(Exception e){
			System.out.println(e.getMessage());
		}finally{
			if(inputStream!=null){
				try {
					inputStream.close();
				} catch (IOException e) {
					System.out.println(e.getMessage());
				}
			}
			if(outputStream!=null){
				try{
					outputStream.close();
				}catch(IOException e){
					System.out.println(e.getMessage());
				}
			}
		}	
	}


下面是使用NIO的一种方式,注释代码行与它的上一行作用是一样的,选择一种就可以了。

这种方式看上去更整洁一些,不过这里有限制条件是上传或者下载的源文件必须提供大小。



/**
	 * 
	 * @param filePath
	 * @param savePath
	 */
	public static void downLoadByFileChannel(String filePath,String savePath){
           FileInputStream fis=null;
           FileOutputStream fos=null;
           FileChannel inChannel=null;
           FileChannel outChannel=null;
           try{
        	   fis=new FileInputStream(filePath); 
               fos=new FileOutputStream(savePath);
               inChannel=fis.getChannel();
               outChannel=fos.getChannel();
               
               outChannel.transferFrom(inChannel, 0, (new File(filePath)).length());
               //inChannel.transferTo(0, (new File(filePath)).length(), outChannel);
           }catch(IOException e){
        	   System.out.println(e.getMessage());
           }finally{        	   
        	   try {
				inChannel.close();
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}
        	   try {
				outChannel.close();
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}
        	   try {
				fis.close();
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}
        	   try {
				fos.close();
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}
           }          
	}


使用web的方式上传下载文件的时候,可以根据是否独占线程,是否阻塞等限制来选择使用NIO/IO. 当使用单独的文本服务器提供文本服务的时候,一般选用NIO的方式,如果只是简单的文件上传下载,选择自己觉得最简单的就可以了。


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值