java - 如果 Java 中的 'Download as zip' 双字节文件名被破坏

标签 java encoding

从远程路径下载文件夹时,文件名出现垃圾字符。

例如:

remote path: "//10.7.456.78/abc/私はライオン"

local path: "C:\Users\test32\Desktop"

'私はライオン' folder contains 2 txt files 

1. はライ.txt  
2. ライ.txt

但在将文件夹下载为 Zip 后,文件名包含垃圾字符,如 ½T½ñ.txt

代码片段:

if(isZip)  {
    int lastIndex = remotePath.lastIndexOf('/');
    filename = remotePath.substring(remotePath.lastIndexOf('/', lastIndex - 1) + 1, lastIndex);
    filename = filename.concat(".zip");
}
File file = new File(localPath + "/" + filename);

if (file.exists())
    return RES_FILE_EXISTS;
else if (!file.createNewFile())
    return -1;

InputStream reader = urlCon.getInputStream();
FileOutputStream writer = new FileOutputStream(file);

// Process body
int count;
long bytesSent = 0;
byte[] inarray = new byte[65534];

long fileSize = ((HttpsURLConnection) urlCon).getContentLength();

/* Initialize data transfer statistics */
long timeStart = System.currentTimeMillis();

while (bytesSent < fileSize && ((count = reader.read(inarray)) > 0) && run)  {
     writer.write(inarray, 0, count);
     bytesSent += count;
}

reader.close();
writer.flush();
writer.close();

如果我下载没有 zip 的文件夹,那么文件名不会损坏。

如果有人能帮我解决这个问题就好了。

最佳答案

很可能远程服务器和本地系统的系统字符编码不匹配,或者彼此不兼容。

另一种可能性是 remotePath 变量存在缺陷。代码片段没有显示 remotePath 变量是如何生成的任何线索。您可以检查 remotePath 变量是否包含正确的字符。

关于java - 如果 Java 中的 'Download as zip' 双字节文件名被破坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20261102/

相关文章:

java - 打印到文本文件

java - 用于添加多个对象实例的可变参数

JavaScript 强制 UTF-8 编码

java - IntelliJ 14 不断将编码切换为 UTF-8

Python 2.7 从utf-8文件读写 "éèàçê"

Java 简单的 boolean[] 到 byte 的转换

java - jSTL 不适用于 activiti 7 - 冲突库

java - 如何按日期从多个文档过滤数据 Firestore、Android、Java

c# - 在 C# 中使用不同类型的编码方案的十六进制字节输出有什么区别?

python - 使utf8在文件中可读