我在将文件移到ftp网站后删除文件时遇到了一些问题。在之前的过程中,我生成文件并将它们放在一个文件夹中。此过程应将每个文件上载到ftp站点,然后删除本地副本。由于原因,我无法弄清楚删除是否失败,但我没有得到任何类型的错误消息或异常。最初我在ftp.put()之后立即调用了file.delete(),但是我把它移动到它的当前位置,认为文件可能被jsch锁定并且调用它会修复它。情况似乎并非如此。理想情况下,呼叫会返回那里,所以我不需要有两个“for”循环。
如果你也碰巧知道为什么覆盖不起作用会产生奖励。当我查看通过实际FTP程序上传的文件时,权限是rw-rw-rw。服务器上的现有文件已通过此过程上传。
以下是代码:
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);
}
}
答案 0 :(得分:6)
使用后您必须 关闭 文件,否则,它将被当前使用组件锁定。
更改此行:
ftp.put(new FileInputStream(file)...
对于在流上调用finally
的{{1}}子句,以确保在任何情况下(好或异常)释放文件:
close
回顾一下:
finally{
fileInput.close();
}
来自docs:
close()关闭此文件输入流并释放所有系统 与流相关的资源。