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();
}
}
Filef = new File(filePath);
if ( ! f.exists()){
response.sendError( 404 , " Filenotfound! " );
return ;
}
BufferedInputStreambr = new BufferedInputStream( new FileInputStream(f));
byte []buf = new byte [ 1024 ];
int len = 0 ;
response.reset(); // 非常重要
if (isOnLine){ // 在线打开方式
URLu = new URL( " 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实现文件下载的不同方法,包括本地文件下载、网络文件下载及在线打开文件的方式,并提供了具体的实现代码。


被折叠的 条评论
为什么被折叠?



