【问题标题】:Make file empty/clear on ftp server after download in Java用 Java 下载后在 ftp 服务器上使文件为空/清除
【发布时间】:2018-09-21 09:46:27
【问题描述】:

我用 Java 编写了以下方法,它为我下载了一个文件, 从服务器到我的本地计算机。

public void downloadcsv() {

    String server = "servername.host";
    int port = 21;
    String user = "username";
    String pass = "password";

    FTPClient ftpClient = new FTPClient();
    try {

        ftpClient.connect(server, port);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        String remoteFile = "/serverpath/daten.csv";
        File downloadFile = new File("localpath/daten.csv");
        OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile));

        boolean success = ftpClient.retrieveFile(remoteFile, outputStream);

        outputStream.close();

        if (success) {
            System.out.println("File has been downloaded successfully.");
        }

    } catch (IOException ex) {

        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();

    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

到目前为止一切顺利。 现在,我想删除服务器上文件的内容。

只是内容,因为我需要用另一个程序将文件写入其中。

有没有一种快速的方法来做到这一点,在下载期间或之后?

现在,我只是用另一种方法删除文件并创建一个新文件。

但这似乎效率低下。 感谢您的帮助。

【问题讨论】:

  • @algoob,解决方法见this,放入if(success)
  • 好的,但我如何在服务器上做到这一点?我想删除服务器上文件的内容。

标签: java file ftp


【解决方案1】:

上传空流清除文件内容:

ftpClient.storeFile("/serverpath/daten.csv", new ByteArrayInputStream(new byte[0]));

实际上,当您“创建一个新文件”时,我相信您一定已经在做类似的事情了。因为没有其他方法可以在 FTP 服务器上“创建文件”。只是没有理由在覆盖之前“删除文件”

【讨论】:

    猜你喜欢
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    相关资源
    最近更新 更多