无法在Java中以其名称下载带有UTF-8字符的文件

时间:2016-05-08 13:17:09

标签: java android android-studio utf-8 cloud

我迫切需要帮助。 在我的Android应用程序中,我在从名称中包含UTF-8字符的服务器下载文件时遇到问题。使用常规字符(英文字母)。服务器接收UTF-8字符为“?”。

示例:

名为“Preview-icon.png”的文件有效,但名为“Preview-iconČ.png”的文件不起作用,我收到“找不到文件错误”,因为它搜索“预览图标?”。 png“而不是”Preview-iconČ“。

我一直在寻找解决方案一周,但我还没有找到它。

以下是我下载文件的代码:

public void downloadFile(String url, String dest_file_path) {
    try {

        File dest_file = new File(dest_file_path);
        URL u = new URL(url);
        URLConnection conn = u.openConnection();
        int contentLength = conn.getContentLength();
        DataInputStream stream = new DataInputStream(u.openStream());
        byte[] buffer = new byte[contentLength];
        stream.readFully(buffer);
        stream.close();
        DataOutputStream fos = new DataOutputStream(new FileOutputStream(dest_file));
        fos.write(buffer);
        fos.flush();
        fos.close();

    } catch(FileNotFoundException e) {

        Log.e("file","not found!");
        return;
    } catch (IOException e) {
        Log.e("IO","error");
        return;
    }

参数url是包含url的常规字符串,例如。 “http://127.0.0.1:10001/downloadfile?filepath=/home/nikola/Desktop/Preview-icon.png&filename=Preview-icon.png”。而dest_file_path是内部存储中位置的终止,例如。 “/mnt/sdcard/Preview-icon.png”。

2 个答案:

答案 0 :(得分:0)

服务器应用程序使用的Charset是什么,似乎客户端和服务器使用的字符集不匹配,请尝试双方都使用UTF-8

答案 1 :(得分:0)

感谢您的帮助,我找到了解决方案。我只需要编码具有UTF-8字符的字符串的一部分。

所以我只使用URLEncode对字符串中的“Preview-iconč.png”进行编码,将其添加到最终字符串中,然后使用bam,就像魅力一样。 :d