【问题标题】:Java FTPClient does not transfer the whole fileJava FTPClient 不传输整个文件
【发布时间】:2015-10-06 09:23:02
【问题描述】:

我写了一个从 FTP 服务器下载文件的 java 类。一切看起来都很好,但是当我检查文件的大小时,它们比原始文件小了一点。

知道为什么会这样吗?

import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.IOException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import java.io.IOException;

public class Downloader {
    public static void main(String[] args) {
        String server = "ftp.example.gov";
        int port = 21;
        String user = "anonymous";
        String pass = "anonymous";
        FTPClient ftpClient = new FTPClient();

        try {
            ftpClient.connect(server, port);
            ftpClient.login(user, pass);
            ftpClient.cwd("dir1/dir2/gz");

            FTPFile[] files = ftpClient.listFiles();

            for (FTPFile file : files) {
                String downloadFile = "/home/andrej/Documents/" + file.getName();
                OutputStream output = new BufferedOutputStream(new FileOutputStream(downloadFile));
                boolean success = ftpClient.retrieveFile(file.getName(), output);
                output.close();
                if (success) {
                    System.out.println(file.getName());
                }
            }

        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

【问题讨论】:

  • 小了多少?可以同时包含两个文件大小吗?
  • 原始文件 (gzip) 大小为 20 MB,下载文件大小为 16 MB。
  • 嗯,它可能没有 4MB 的回车...

标签: java ftp ftp-client


【解决方案1】:

尝试以二进制模式下载,您的差异可能是由于两个服务器之间的回车符不同。如果您的服务器是 Windows,您将拥有 CRLF,而 Linux 将只有 New Line。 ASCII 模式的 FTP 会自动为您进行转换。

当您比较两个文件时,它们在文本上是否相同?如果是这样,我认为您不必担心。

【讨论】:

  • ftpClient.setFileType(FTP.BINARY_FILE_TYPE); 行解决了这个问题。现在就像一个魅力。
【解决方案2】:

在 output.close() 之前尝试 output.flush() 将最后缓冲的字节写入文件。为我工作! FTP.BINARY_FILE_TYPE 没有。

【讨论】:

    猜你喜欢
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    • 2012-11-06
    • 2012-07-19
    • 2013-07-07
    • 2013-04-07
    相关资源
    最近更新 更多