abcdefg1112aa 2011-08-12 11:03
浏览 221
已采纳

java 下载服务器文件到本地 中文无法识别

[color=red][size=large]下面是我的代码,如果url当中没有中文则可以下载,如果有则出错。InputStream in = con.getInputStream();这一句出错。
这个是编码问题,我上网找了很多资料,但是还是不会改,对编码的原理还不是很了解。哪位帮忙改改,谢谢![/size][/color]
[code="java"]import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class download {

public static void DownloadFile(URL theURL, String filePath) throws IOException {
    URLConnection con = theURL.openConnection();
    String urlPath = con.getURL().getFile();
    String fileFullName = urlPath.substring(urlPath.lastIndexOf("/") + 1);
    if (fileFullName != null) {
        byte[] buffer = new byte[4 * 1024];
        int read;
        String path = filePath + "/" + fileFullName;
        File fileFolder = new File(filePath);
        if(!fileFolder.exists()){
            fileFolder.mkdir();
        }
        InputStream in = con.getInputStream();
        FileOutputStream os = new FileOutputStream(path);
        while ((read = in.read(buffer)) > 0) {
            os.write(buffer, 0, read);
        }
        os.close();
        in.close();
        long end = System.currentTimeMillis();
    } else {
    }
}

public static void main(String[] args) {
    String urlS = "http://172.18.33.133:8080/zh/中文.jpg";
    String filePathString = "d:/中文";
    URL url;
    try {
        url = new URL(urlS);
        try {
            DownloadFile(url,filePathString);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

}

}[/code]

  • 写回答

3条回答 默认 最新

  • laopeng301 2011-08-12 11:45
    关注

    [code="java"]
    String urlS = "http://172.18.33.133:8080/zh/中文.jpg";

    把文件名編碼成你服務器端一樣啊·主機不要編碼·
    String host="http://172.18.33.133:8080/zh/";
    String filename=java.net.Encoder.encode("中文.jpg","服務器斷編碼·");
    String urlS = host+filename;
    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀