Java Apache FTPClient 大多数下载的文件为空或丢失

Java Apache FTPClient most downloaded files are empty or missing

这是我的代码,应该将整个 FTP 目录下载到本地文件夹。它做得很好,但大多数文件的大小为 0KB。只有 JSON 个文件似乎包含所有数据。

我尝试过的事情:

  1. 更改 FTP 文件类型 client.setFileType("FTP.BINARY_FILE_TYPE");
  2. 使用 OutputStream 代替 FileOutputStream

代码:

public static void copyFolder(File destination, FTPFile sourceFile, FTPClient ftpClient) throws IOException{
    if (!sourceFile.isDirectory()) {
        //copy file
        File downloadFile = new File(destination + "/"+ sourceFile.getName());
        String remoteFile =  sourceFile.getName();
        FileOutputStream outputStream = new FileOutputStream(downloadFile);
        System.out.println(remoteFile);
        System.out.println(downloadFile.getPath());
        boolean success = ftpClient.retrieveFile(remoteFile, outputStream);
        if(success) {
            System.out.println("Retrieved " + remoteFile);
        }
        outputStream.close();
    }else{
        //loop through a subdirectory
        ftpClient.changeWorkingDirectory(ftpClient.printWorkingDirectory() + "/" + sourceFile.getName());
        System.out.println(ftpClient.printWorkingDirectory());
        FTPFile[] contents = ftpClient.listFiles(ftpClient.printWorkingDirectory());
        File newDest = new File(destination + "/" + sourceFile.getName());
        if(!newDest.exists()){
            newDest.mkdir();
        }
        for(FTPFile file : contents){
            copyFolder(newDest, file, ftpClient);
        }
        return;
    }
}

如何正确获取转账?

尝试在同一台计算机上下载它,但在文件下载之间和下载过程中几次断开连接。此外,似乎很少有文件被下载。我会把问题的标题改得更具体。

由于某种原因只复制了两个文件 – https://pastebin.com/XNWqRMDj它们不是空的。

问题出在您的 changeWorkingDirectory 电话上。大部分时间都在失败。

ftpClient.changeWorkingDirectory(ftpClient.printWorkingDirectory() + "/" + sourceFile.getName());

应该是:

ftpClient.changeWorkingDirectory(destination + "/" + sourceFile.getName());

有关在 Java 中下载 FTP 个文件夹的完整工作代码,请参阅:
Download all folders recursively from FTP server in Java