博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java IO/NIO 下载上传的笔记
阅读量:4038 次
发布时间:2019-05-24

本文共 2290 字,大约阅读时间需要 7 分钟。

传统古老的上传下载方式大概主要是用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的方式,如果只是简单的文件上传下载,选择自己觉得最简单的就可以了。

转载地址:http://sepdi.baihongyu.com/

你可能感兴趣的文章
LED恒流驱动芯片
查看>>
驱动TFT要SDRAM做为显示缓存
查看>>
使用file查看可执行文件的平台性,x86 or arm ?
查看>>
qt5 everywhere 编译summary
查看>>
qt5 everywhere编译完成后,找不到qmake
查看>>
arm-linux开机读取硬件时钟,设置系统时钟。
查看>>
交叉编译在x86上调试好的qt程序
查看>>
qt 创建异形窗体
查看>>
可重入函数与不可重入函数
查看>>
简单Linux C线程池
查看>>
内存池
查看>>
输入设备节点自动生成
查看>>
GNU hello代码分析
查看>>
Qt继电器控制板代码
查看>>
wpa_supplicant控制脚本
查看>>
gstreamer相关工具集合
查看>>
arm 自动升级脚本
查看>>
RS232 四入四出模块控制代码
查看>>
gstreamer插件之 videotestsrc
查看>>
autoupdate script
查看>>