Java SFTP / SSH目录不会删除/删除目录

时间:2014-10-24 14:57:23

标签: java ssh jsch

我到处尝试谷歌搜索,但找不到任何地方。 我想要完成的是去SFTP或SSH并删除/删除目录。

这是我的代码。任何帮助表示赞赏。此代码不会删除和删除目录,因为它假设这样做。

public static boolean removeDirectory(String path, Session session) throws InterruptedException {

        ChannelExec channelExec = null;
        try {
            channelExec = (ChannelExec) session.openChannel("exec");

            String command = "rm -rf "+path;
            channelExec.setCommand(command);


            channelExec.connect();
            Thread.sleep(5000); 
            channelExec.disconnect();
        } catch (JSchException e1) {
            return false;
        }               
        return true;
    }

1 个答案:

答案 0 :(得分:0)

我终于得到了解决方案。我已经使用jScape库递归删除目录

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 SFTPExample extends SftpAdapter {
     static String hostName = "hostname";
     static String username = "username";
     static String password = "password";;
     static String directory = "directory";;
    private static Sftp sftp;

    private static org.apache.log4j.Logger log = Logger.getLogger(SFTPExample.class);

    @SuppressWarnings("unchecked")
    public static boolean deleteDir(List <String> path) throws SftpException {
        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(" ------ File Name: " + eachOne);
                System.out.println(directory+eachOne);
                sftp.deleteDir(directory+eachOne, true);
            }
        }

        sftp.disconnect();
        log.info("------------------------ file(s) delete finished -----------------------");

        return true;
    }

    // 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();
    }
}