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

时间:2014-03-04 08:41:56

标签: java ssh sftp apache-commons

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

3 个答案:

答案 0 :(得分:2)

我不完全确定它是否具有本机递归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();

频道有rm()和rmdir()。

答案 1 :(得分:1)

不幸的是,sftp协议不允许删除非空目录, 并且jsch没有实现这些目录的递归删除。如果你不想自己实现递归删除,那么如何在jsch的exec通道上执行“rm -rf”呢?

答案 2 :(得分:1)

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

channelSftp.cd(path); // Change Directory on SFTP Server
    // List source directory structure.
    Vector<ChannelSftp.LsEntry> fileAndFolderList = channelSftp.ls(path); 

    // Iterate objects in the list to get file/folder names.
    for (ChannelSftp.LsEntry item : fileAndFolderList) { 

        // If it is a file (not a directory).
        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(path + "/" + item.getFilename()); 
            }
        }
    }

    channelSftp.rmdir(path); // delete the parent directory after empty

了解更多详情。请参阅链接here