当前位置: 代码迷 >> 综合 >> java IO/NIO 下载上传的笔记
  详细解决方案

java IO/NIO 下载上传的笔记

热度:1   发布时间:2024-01-15 16:32:02.0

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