JAVA实现下载文件功能的两种方法
第一种方法:
publicHttpServletResponsedownload(Stringpath,HttpServletResponseresponse){ try{ //path是指欲下载的文件的路径。 Filefile=newFile(path); //取得文件名。 Stringfilename=file.getName(); //取得文件的后缀名。 Stringext=filename.substring(filename.lastIndexOf(".")+1).toUpperCase(); //以流的形式下载文件。 InputStreamfis=newBufferedInputStream(newFileInputStream(path)); byte[]buffer=newbyte[fis.available()]; fis.read(buffer); fis.close(); //清空response response.reset(); //设置response的Header response.addHeader("Content-Disposition","attachment;filename="+newString(filename.getBytes())); response.addHeader("Content-Length",""+file.length()); OutputStreamtoClient=newBufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); toClient.write(buffer); toClient.flush(); toClient.close(); }catch(IOExceptionex){ ex.printStackTrace(); } returnresponse; } publicvoiddownloadLocal(HttpServletResponseresponse)throwsFileNotFoundException{ //下载本地文件 StringfileName="Operator.doc".toString();//文件的默认保存名 //读到流中 InputStreaminStream=newFileInputStream("c:/Operator.doc");//文件的存放路径 //设置输出的格式 response.reset(); response.setContentType("bin"); response.addHeader("Content-Disposition","attachment;filename=\""+fileName+"\""); //循环取出流中的数据 byte[]b=newbyte[100]; intlen; try{ while((len=inStream.read(b))>0) response.getOutputStream().write(b,0,len); inStream.close(); }catch(IOExceptione){ e.printStackTrace(); } } publicvoiddownloadNet(HttpServletResponseresponse)throwsMalformedURLException{ //下载网络文件 intbytesum=0; intbyteread=0; URLurl=newURL("windine.blogdriver.com/logo.gif"); try{ URLConnectionconn=url.openConnection(); InputStreaminStream=conn.getInputStream(); FileOutputStreamfs=newFileOutputStream("c:/abc.gif"); byte[]buffer=newbyte[1204]; intlength; while((byteread=inStream.read(buffer))!=-1){ bytesum+=byteread; System.out.println(bytesum); fs.write(buffer,0,byteread); } }catch(FileNotFoundExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } }
第二种方法:
publicvoiddownLoad(StringfilePath,HttpServletResponseresponse,booleanisOnLine)throwsException{ Filef=newFile(filePath); if(!f.exists()){ response.sendError(404,"Filenotfound!"); return; } BufferedInputStreambr=newBufferedInputStream(newFileInputStream(f)); byte[]buf=newbyte[1024]; intlen=0; response.reset();//非常重要 if(isOnLine){//在线打开方式 URLu=newURL("file:///"+filePath); response.setContentType(u.openConnection().getContentType()); response.setHeader("Content-Disposition","inline;filename="+f.getName()); //文件名应该编码成UTF-8 }else{//纯下载方式 response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition","attachment;filename="+f.getName()); } OutputStreamout=response.getOutputStream(); while((len=br.read(buf))>0) out.write(buf,0,len); br.close(); out.close(); }
以上就是JAVA实现下载文件功能的两种方法的详细内容,更多关于JAVA实现下载文件的资料请关注毛票票其它相关文章!