我尝试使用 JSCH 通过 SFTP 删除非空文件夹,但没有成功。
这个可以用,但不是免费的:(我已经过了 30 天的试用期。我的公司拒绝向他们支付仅通过 SFTP 删除文件夹的费用。
package com.test.cvsutil;
import java.util.List;
import org.apache.log4j.Logger;
import com.jscape.inet.sftp.Sftp;
import com.jscape.inet.sftp.SftpException;
import com.jscape.inet.sftp.events.SftpAdapter;
import com.jscape.inet.ssh.util.SshParameters;
public class SFTPFileDeleter extends SftpAdapter {
static String hostName = ServerProperties.getProperty("test.ftp.hostname");
static String username = ServerProperties.getProperty("test.ftp.login");
static String password = ServerProperties.getProperty("test.ftp.password");
static String directory = ServerProperties.getProperty("test.ftp.directory");
private static Sftp sftp;
private static org.apache.log4j.Logger log = Logger.getLogger(SFTPFileDeleter.class);
public static boolean deleteDir(List <String> path) throws SftpException {
Boolean flag = false;
log.info("------------------------ file(s) delete started ------------------------");
sftp = new Sftp(new SshParameters(hostName, username, password));
sftp.connect();
sftp.setDir(directory);
for (String eachOne : path) {
if (!sftp.getDirListingAsString(eachOne).equals("")){
log.info(" ------ Deleted Folder/Scenario Name: " + eachOne);
//log.info(" ------ check file path: " + directory+eachOne);
//System.out.println(directory+eachOne);
sftp.deleteDir(directory+eachOne, true);
flag = true;
}
}
sftp.disconnect();
log.info("------------------------ file(s) delete finished -----------------------");
return flag;
}
// open connection to the remote server.
public static void openConnection() throws SftpException {
sftp.connect();
}
// disconnect from the remote server.
public static void closeConnection() {
sftp.disconnect();
}
}
这是我得到的错误,所以jscape sftp
对我不起作用。
2014-11-29 09:00:04 ERROR MainEntry:47 - There was error and message is java.lang.RuntimeException: Your Secure FTP Factory license expired on Sun Nov 23 00:31:21 CST 2014. Please v
isit http://www.jscape.com to purchase a licensed copy.
2014-11-29 09:00:04 ERROR MainEntry:48 - There was error and stack-trace is [Ljava.lang.StackTraceElement;@fdb00d
非常感谢任何帮助。在这里询问是否有人知道其他可以删除非空文件夹的库。
最佳答案
我能够递归删除该目录。谢谢@Rob
如果有人在寻找它,这里的代码将会有所帮助。
public static void deleteDirectory(ChannelSftp sftp, String oldestBackup) throws SftpException {
if (isDir(sftp, oldestBackup)) {
sftp.cd(oldestBackup);
Vector < LsEntry > entries = sftp.ls(".");
for (LsEntry entry: entries) {
deleteDirectory(sftp, entry.getFilename());
}
sftp.cd("..");
sftp.rmdir(oldestBackup);
} else {
sftp.rm(oldestBackup);
}
}
private static boolean isDir(ChannelSftp sftp, String entry) throws SftpException {
return sftp.stat(entry).isDir();
}
关于java - SFTP非空文件夹递归删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27232739/