成功上传到FTP后我无法删除本地文件(所以我的目标是在上传完成后立即删除本地文件)。 我怀疑FileInputStream阻止本地文件,但我不确定。 也许还有其他我看不到的东西。 任何帮助都没问题。 我正在使用org.apache.commons.net.ftp.FTP。 这是我的代码的一部分:
public class FtpConnection {
String FTP_SERVER;
String FTP_USER;
String FTP_PASSWORD;
int FTP_PORT;
public FTPClient ftpClient;
int attempts = 3;
long FILE_SIZE;
public FtpConnection(String ftp_server, String ftp_user, String ftp_password, int ftp_port) {
FTP_SERVER = ftp_server;
FTP_USER = ftp_user;
FTP_PASSWORD = ftp_password;
FTP_PORT = ftp_port;
ftpClient = new FTPClient();
ftpClient.enterLocalPassiveMode();
ftpClient.setBufferSize(1024 * 1024 * 1024);
ftpClient.setConnectTimeout(120000);
ftpClient.setDataTimeout(60000);
try {
ftpClient.connect(FTP_SERVER, FTP_PORT);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Operation failed. Server reply code: " + replyCode);
return;
}
boolean success = ftpClient.login(FTP_USER, FTP_PASSWORD);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
if (!success) {
System.out.println("Could not login to the server");
}
} catch (IOException ex) {
System.out.println("Oops! Something wrong happened");
ex.printStackTrace();
}
}
public boolean copyFile(File source, String destination) {
try {
FILE_SIZE = source.length();
for(int i=0;i<attempts;i++) {
FileInputStream file = new FileInputStream(source);
ftpClient.storeFile(destination, file);
for(FTPFile f : ftpClient.listFiles()) {
if(f.getName().equals(destination) && f.getSize() == source.length()) {
file.close();
return true;
}
}
}
ftpClient.deleteFile(destination + "/" + source.getName());
return false;
} catch (IOException ex) {
Logger.getLogger(FtpConnection.class.getName()).log(Level.SEVERE, null, ex);
this.closeConnection();
return false;
}
}
}
在这里我调用copyFile方法:
File f = new File("myfile.txt");
boolean b = FTP.copyFile(ORIG,filename);
if(b) {
System.out.println(f.exists()); //true
System.out.println(f.canWrite()); //true
System.out.println(f.delete()); //false
}