【问题标题】:Word Documents Will Not Open After Downloading Using Apache Commons and Java FTP [duplicate]使用 Apache Commons 和 Java FTP 下载后 Word 文档将无法打开 [重复]
【发布时间】:2019-09-30 05:02:04
【问题描述】:

我已按照 Apache 教程使用 Java 从 FTP 下载文档。我尝试了两种方法,它们都下载了文件,如果我使用 Filezilla 检查文件,则报告的文件大小与我在 FTP 客户端中看到的大小相同。但是,当我在本地磁盘上获取文件然后打开它们时,Word 会抛出错误并询问我是否要恢复文档。即使恢复确实有效,我也需要首先正确下载文件。有人能解释一下为什么会发生这种情况吗?

这里是来源:

    private void downloadAllFiles() throws IOException{
    client.enterLocalPassiveMode();
    client.changeWorkingDirectory(ftpDirectory);
    client.setFileStructure(FTP.BINARY_FILE_TYPE);  
    FTPFile[] files = client.listFiles();
    for(FTPFile f : files) {
        if(f.isFile())
            downloadFile(f);
    }
}

    private void downloadFile(FTPFile ftpFile) throws IOException{
    File saveLocation = new File(fileStorageDir);
    if(!saveLocation.exists())
        saveLocation.mkdirs();
    File downloadFile = new File(fileStorageDir + "\\" + ftpFile.getName());
    OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile));
    InputStream inputStream = client.retrieveFileStream(ftpFile.getName());
    byte[] bytesArray = new byte[4096];
    int bytesRead = -1;
    while((bytesRead = inputStream.read(bytesArray)) !=-1) {
        outputStream.write(bytesArray, 0, bytesRead);
    }
    boolean success = client.completePendingCommand();
    if (success) {
        System.out.println("File has been downloaded successfully.");
    }
    outputStream.close();
    inputStream.close();
}

文件名中也有奇数字符。在 FTP 服务器上是这样的

How the Filenames Should Look

当我通过 Java 保存它们时(我尝试过的任何一种方法),它们在我想要删除的文件名中有奇怪的字符:

Local File Names With Odd Characters

我们将不胜感激任何关于这些问题的建议。感谢您的帮助。

【问题讨论】:

    标签: java ftp


    【解决方案1】:

    应该是

    client.setFileType(FTP.BINARY_FILE_TYPE);
    

    不是

    client.setFileStructure(FTP.BINARY_FILE_TYPE);  
    

    【讨论】:

    • 谢谢你。你是对的。现在可以了。我仍然在下载的文件名中有奇怪的字符,但至少它们打开了。
    【解决方案2】:

    修复奇怪的文件名:

    client.setControlEncoding("UTF-8");
    

    【讨论】:

    • 这也解决了这个问题。谢谢。
    • 这不是问题“Word 文档在使用 Apache Commons 和 Java FTP 下载后无法打开”的答案
    猜你喜欢
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-24
    • 2013-10-18
    • 1970-01-01
    相关资源
    最近更新 更多