java实现下载文件,如果文件名为中文,下载后内容为空,求解释!
BufferedInputStreambis=null;BufferedOutputStreambos=null;HttpURLConnectionconn=null;p...
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
HttpURLConnection conn=null;
path=path.replaceAll("%20", " ");
try {
URL url=new URL(path);
conn=(HttpURLConnection) url.openConnection();
conn.setConnectTimeout(6000); //设置连接超时时间6s
conn.connect();
//response.reset();
response.setContentType("application/x-msdownload;");
response.addHeader("Content-Disposition","attachment;filename=\""+new String(fileName.getBytes("gb2312"),"iso8859-1")+"\"");
response.setContentType("application/octet-stream");
bis=new BufferedInputStream(conn.getInputStream());
byte[] buffer = new byte[bis.available()];
int len;
bos = new BufferedOutputStream(response.getOutputStream());//new FileOutputStream(fileName);
while((len = bis.read(buffer))!=-1){
bos.write(buffer,0,len);
}
bos.flush();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{ //关闭各类流
if(conn!=null){
conn.disconnect();
}
if(bis!=null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bos!=null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
当下载中文文件名的文件时,程序报错,如图,所示为出错的地方。 展开
BufferedOutputStream bos=null;
HttpURLConnection conn=null;
path=path.replaceAll("%20", " ");
try {
URL url=new URL(path);
conn=(HttpURLConnection) url.openConnection();
conn.setConnectTimeout(6000); //设置连接超时时间6s
conn.connect();
//response.reset();
response.setContentType("application/x-msdownload;");
response.addHeader("Content-Disposition","attachment;filename=\""+new String(fileName.getBytes("gb2312"),"iso8859-1")+"\"");
response.setContentType("application/octet-stream");
bis=new BufferedInputStream(conn.getInputStream());
byte[] buffer = new byte[bis.available()];
int len;
bos = new BufferedOutputStream(response.getOutputStream());//new FileOutputStream(fileName);
while((len = bis.read(buffer))!=-1){
bos.write(buffer,0,len);
}
bos.flush();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{ //关闭各类流
if(conn!=null){
conn.disconnect();
}
if(bis!=null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bos!=null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
当下载中文文件名的文件时,程序报错,如图,所示为出错的地方。 展开
3个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |