0

I wrote the following method with Java which download a file for me, from the Server to my local computer.

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();
        }
    }
}

So far so good. Now, I want to delete the content of the file on the server.

Just the content, because I need the file to write in it with another program.

Is there a fast way to do that, while or after the download?

Now, I just delete the file with another method and create a new file.

But that seems to be inefficient. Thanks for help.

algoob
  • 1
  • 2
  • 1
    @algoob, See [this](https://stackoverflow.com/a/6994568/5813861) for solution, put it in `if(success)`. – yash Sep 21 '18 at 09:56
  • ok, but how can I do that on the server? I want to delete the content of the file which is on the server. – algoob Sep 21 '18 at 12:12

1 Answers1

0

Upload an empty stream to clear a file contents:

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

Actually I believe you must be doing something like that already, when you "create a new file". As there's no other way to "create a file" on FTP server. Just that there's no reason to "delete the file", before you overwrite it.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992