使用 Java 和 SFTP 删除远程非空文件夹

Hec*_*tor 4 java ssh sftp apache-commons

我需要删除多个 UNIX 服务器上的多个非空文件夹。我希望使用像 Apache FileUtils 这样的东西,它允许删除非空的 LOCAL 文件夹。只是在这种情况下我的文件夹是远程的。我是否必须首先列出每个远程文件夹中包含的所有文件,依次删除找到的每个文件?或者...是否有一个 java SFTP/SSH 客户端可以公开 FileUtils.deleteDirectory() 的功能以进行远程文件夹删除?

小智 9

您可以使用JSCH java API删除文件夹。下面是用java和SFTP删除非空文件夹的示例代码。

@SuppressWarnings("unchecked")
private static void recursiveFolderDelete(ChannelSftp channelSftp, String path) throws SftpException {

    // List source directory structure.
    Collection<ChannelSftp.LsEntry> fileAndFolderList = channelSftp.ls(path);

    // Iterate objects in the list to get file/folder names.
    for (ChannelSftp.LsEntry item : fileAndFolderList) {
        if (!item.getAttrs().isDir()) {
            channelSftp.rm(path + "/" + item.getFilename()); // Remove file.
        } else if (!(".".equals(item.getFilename()) || "..".equals(item.getFilename()))) { // If it is a subdir.
            try {
                // removing sub directory.
                channelSftp.rmdir(path + "/" + item.getFilename());
            } catch (Exception e) { // If subdir is not empty and error occurs.
                // Do lsFolderRemove on this subdir to enter it and clear its contents.
                recursiveFolderDelete(channelSftp, path + "/" + item.getFilename());
            }
        }
    }
    channelSftp.rmdir(path); // delete the parent directory after empty
}
Run Code Online (Sandbox Code Playgroud)

更多细节。请参考这里的链接


nab*_*lex 5

我不完全确定它是否具有本机递归 delete()(虽然这对于自己实现很简单)但是 jsch(http://www.jcraft.com/jsch/)是一个很棒的实现,它允许 sftp 访问。我们一直在使用它。

连接示例代码:

JSch jsch = new JSch();
Properties properties = new Properties();
properties.setProperty("StrictHostKeyChecking", "no");

if (privKeyFile != null)
    jsch.addIdentity(privKeyFile, password);

Session session = jsch.getSession(username, host, port);
session.setTimeout(timeout);
session.setConfig(properties);

if (proxy != null)
    session.setProxy(proxy);

if (privKeyFile == null && password != null)
    session.setPassword(password);

session.connect();

ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();
Run Code Online (Sandbox Code Playgroud)

通道有 rm() 和 rmdir()。