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

  • 本文关键字:删除 SFTP Java SSH 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;
    }

我终于得到了解决方案。我已经使用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();
    }
}

最新更新