在 Java 中下载后,在 ftp 服务器上使文件为空/清除



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

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

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

有没有一种快速的方法可以做到这一点,在下载时或之后?

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

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

上传空流以清除文件内容:

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

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

最新更新