I have a requirement to delete multiple non empty folders on multiple UNIX servers. I am looking to use something like Apache FileUtils, which allows non empty LOCAL folders to be deleted. Its just that my folders in this case are REMOTE. Do i have to first list all the files contained in each remote folder, deleting each file found in turn? Or... Is there a java SFTP/SSH client that exposes the functionality of FileUtils.deleteDirectory() for remote folder removal?
You can delete folder using JSCH java API. Below is the sample code for deleting non empty folder with java and 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
}
For more details. Please refer the link here
I'm not entirely sure if it has a native recursive delete() (this is trivial to implement yourself though) but jsch (http://www.jcraft.com/jsch/) is an awesome implementation that allows for sftp access. We use it all the time.
Example code for connection:
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();
The channel has rm() and rmdir().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With