Reputation: 1467
I'm having some issues with removing files after moving them to an ftp site. In a previous process I am generating files and putting them in a folder. This process should upload every file to the ftp site and then delete the local copy. For reasons I can't figure out the delete is failing but I'm not getting any sort of error message or exception. Originally I had the file.delete() call right after the ftp.put() but I moved it to it's current location thinking that maybe the file was locked by jsch and putting the call there would fix it. That doesn't seem to be the case. Ideally the call would go back there so I don't need to have two "for" loops.
If you also happen to know why the overwrite is not working that would be a bonus. When i look at the files uploaded through an actual FTP program the rights are rw-rw-rw. The existing files on the server were already uploaded through this process.
Here is the code:
JSch jsch = new JSch();
Session session = null;
try {
File sourceDir = new File(certSourceFolder);
if (!sourceDir.exists()) {
sourceDir.mkdirs();
}
session = jsch.getSession(ftpUser, ftpServer, 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(ftpPassword);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp ftp = (ChannelSftp) channel;
ftp.cd(certDestFolder);
for (File file : sourceDir.listFiles()) {
if (file.isFile()) {
try {
ftp.put(new FileInputStream(file), file.getName(), ChannelSftp.OVERWRITE);
} catch (SftpException ex) {
//The overwrite is not working. For now I'm just going to trap the error and move on. This really shouldn't happen ever since I delete the file once uploaded.
if (!ex.getMessage().equalsIgnoreCase("Permission denied"))
throw ex;
}
}
}
ftp.exit();
session.disconnect();
//TODO: this is not working. figure out why. If possible get rid of this and move the file.delete up to after ftp.put
for (File file : sourceDir.listFiles()) {
if (file.isFile()) {
file.delete();
}
}
} catch (Exception e) {
DefaultLogger.logException("CertificateFileTransfer", e);
}
}
Upvotes: 1
Views: 3540
Reputation: 13013
You must close the file after using it, otherwise, it will be locked by the current using component.
Change this line:
ftp.put(new FileInputStream(file)...
To a finally
clause that calling close
on the stream in order to ensure the release of the file in any case (good or exception):
finally{
fileInput.close();
}
To recap:
FileInputStream fileInput = null;
try {
fileInput = new FileInputStream(file);
ftp.put(fileInput, file.getName(), ChannelSftp.OVERWRITE);
} catch (SftpException ex) {
if (!ex.getMessage().equalsIgnoreCase("Permission denied"))
throw ex;
}
finally{
if(fileInput != null){
fileInput.close();
}
}
From docs:
close() Closes this file input stream and releases any system resources associated with the stream.
Upvotes: 8