Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
621 views
in Technique[技术] by (71.8m points)

java - Transfer folder and subfolders using ChannelSftp in JSch?

I want to transfer a folder and a subfolder using JSch ChannelSftp. I can successfully transfer files using channelsftp.put(src, dest) command but this does not work for folders (at least I could not make it work). So can someone please explain how can I transfer folders and subfolders using ChannelSftp?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To work with multilevel folder structures in jsch you:

  1. enter them;
  2. list their contents;
  3. do smth with every found item;
  4. repeat 1, 2 & 3 if subfolder is found.

DOWNLOAD dirs method inside your JSCH class:

public void downloadDir(String sourcePath, String destPath) throws SftpException { // With subfolders and all files.
    // Create local folders if absent.
    try {
        new File(destPath).mkdirs();
    } catch (Exception e) {
        System.out.println("Error at : " + destPath);
    }
    sftpChannel.lcd(destPath);

    // Copy remote folders one by one.
    lsFolderCopy(sourcePath, destPath); // Separated because loops itself inside for subfolders.
}

private void lsFolderCopy(String sourcePath, String destPath) throws SftpException { // List source (remote, sftp) directory and create a local copy of it - method for every single directory.
    Vector<ChannelSftp.LsEntry> list = sftpChannel.ls(sourcePath); // List source directory structure.
    for (ChannelSftp.LsEntry oListItem : list) { // Iterate objects in the list to get file/folder names.
        if (!oListItem.getAttrs().isDir()) { // If it is a file (not a directory).
            if (!(new File(destPath + "/" + oListItem.getFilename())).exists() || (oListItem.getAttrs().getMTime() > Long.valueOf(new File(destPath + "/" + oListItem.getFilename()).lastModified() / (long) 1000).intValue())) { // Download only if changed later.
                new File(destPath + "/" + oListItem.getFilename());
                sftpChannel.get(sourcePath + "/" + oListItem.getFilename(), destPath + "/" + oListItem.getFilename()); // Grab file from source ([source filename], [destination filename]).
            }
        } else if (!(".".equals(oListItem.getFilename()) || "..".equals(oListItem.getFilename()))) {
            new File(destPath + "/" + oListItem.getFilename()).mkdirs(); // Empty folder copy.
            lsFolderCopy(sourcePath + "/" + oListItem.getFilename(), destPath + "/" + oListItem.getFilename()); // Enter found folder on server to read its contents and create locally.
        }
    }
}

REMOVE dirs method inside your JSCH class:

try {
    sftpChannel.cd(dir);
    Vector<ChannelSftp.LsEntry> list = sftpChannel.ls(dir); // List source directory structure.
    for (ChannelSftp.LsEntry oListItem : list) { // Iterate objects in the list to get file/folder names.
        if (!oListItem.getAttrs().isDir()) { // If it is a file (not a directory).
            sftpChannel.rm(dir + "/" + oListItem.getFilename()); // Remove file.
        } else if (!(".".equals(oListItem.getFilename()) || "..".equals(oListItem.getFilename()))) { // If it is a subdir.
            try {
                sftpChannel.rmdir(dir + "/" + oListItem.getFilename());  // Try removing subdir.
            } catch (Exception e) { // If subdir is not empty and error occurs.
                lsFolderRemove(dir + "/" + oListItem.getFilename()); // Do lsFolderRemove on this subdir to enter it and clear its contents.
            }
        }
    }
    sftpChannel.rmdir(dir); // Finally remove the required dir.
} catch (SftpException sftpException) {
    System.out.println("Removing " + dir + " failed. It may be already deleted.");
}

CALL these methods from outside like:

MyJSCHClass sftp = new MyJSCHClass();
sftp.removeDir("/mypublic/myfolders");
sftp.disconnect(); // Disconnecting is obligatory - otherwise changes on server can be discarded (e.g. loaded folder disappears).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...