您的位置:首页 > 编程语言 > Java开发

java下载远程服务器中以中文命名的文件

2014-08-01 15:05 501 查看
远程服务器使用的是Tomcat 6.0.18,但是Tomcat 默认是不支持中文文件名访问。

(一)修改Tomcat配置文件方法:

找到Tomcat 目录,打开config/server.xml文件,添加一段代码即可。如红色的字体

<Connector port="8080"

URIEncoding="utf-8"

protocol="HTTP/1.1"

connectionTimeout="20000"

redirectPort="8443" />

这段代码规定了Tomcat监听HTTP请求的端口号等信息,可以在这里添加一个属性:URIEncoding,将该属性值设置为UTF-8,即可让Tomcat不再以ISO-8859-1的编码处理get请求。更改后的代码(红色部分为新添加的代码)

(二)Java代码实现

java.net.URLConnection和java.net.URL是远程读取文件重要的类。因为当前的文件名是中文,如果直接构造字符串http://localhost/download/中文文件.xxx 读取远程文件必然要出错。需要对"中文文件.xxx"进行编码,如下代码:

URLEncoder.encode("中文文件.xxx", "utf-8");

//输入结果为:%E4%B8%AD%E6%96%87%E6%96%87%E4%BB%B6.xxx

所以,构造new java.net.URL( "http://localhost/download/%E4%B8%AD%E6%96%87%E6%96%87%E4%BB%B6.xxx");此时远程请求数据才不会出错

附上测试用不完善代码:

import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class test {
public static void main(String[] args) throws IOException {
/**
* 下面那个url中只要包含中文文件,下载就会出错
*/
long start = System.currentTimeMillis();
String path = "http://112.124.111.3/xcSchool/upload/"; // 从远程服务器上下载的文件路径
// String url="http://112.124.111.3/xcSchool/upload/1.gif";
// //从远程服务器上下载的文件路径
String filenamecn = URLEncoder.encode("我们.gif", "utf-8");
String filePath = "C:\\down"; // 保存地址
URL url = new URL(path + filenamecn);
HttpURLConnection con =  (HttpURLConnection) url.openConnection();
String urlPath = con.getURL().getFile();
System.out.println(urlPath);
String fileFullName = urlPath.substring(urlPath.lastIndexOf("/") + 1);
System.out.println(fileFullName);
if (fileFullName != null) {
byte[] buffer = new byte[4 * 1024];
int read;
String localpath = filePath + "\\" + fileFullName;
File fileFolder = new File(filePath);
if (!fileFolder.exists()) {
fileFolder.mkdirs();
}
DataOutputStream dos = new DataOutputStream(new FileOutputStream(localpath));
BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
System.out.println("正在接收文件...");
while ((read = bis.read(buffer)) > 0){//循环获取文件
dos.write(buffer, 0, read);
}
System.out.println("共用时:" +
(System.currentTimeMillis() - start) / 1000);
dos.close();
bis.close();
con.disconnect();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: