Search code examples
javaftpjsch

How can I recursively FTP a directory structure using Jsch?


I'm trying to traverse a directory and upload all contents and directories in the same structure.

This is an example structure:

Dir1/
....Dir1_1/
....Dir1_2/
........Dir1_2_1/
............file.txt
Dir2/
....file.txt
....file2.txt
Dir3/
Dir4/
index.html
index.css
example.file

I've tried the following:

private void ftpFiles(File[] files, ChannelSftp channelSftp) throws SftpException, FileNotFoundException {
    for (File file : files) {
        System.out.println("Uploading: " + file.getName());

        if (file.isDirectory()) {
            System.out.println(file.getName() + " is a directory");
            SftpATTRS attrs;
            try {
                channelSftp.stat(file.getName());
            } catch (Exception e) {
                System.out.println(file.getName() + " does not exist. Creating it...");
                channelSftp.mkdir(file.getName());
            } 
            channelSftp.cd(file.getName());

            this.ftpFiles(file.listFiles(), channelSftp);
        } else {
            channelSftp.put(new FileInputStream(file), file.getName());
        }
    }
}

I'm taking an array of top level files, and recursively going down each one.

The problem is once I hit the first directory and cd into it, all further files and directories are inside of this.

Example: /Dir1/Dir1_1/Dir1_2/Dir1_2_1/Dir2/Dir3/Dir4/...etc

How can I do a ../ with my channel while calling this recursively?


Solution

  • Maybe something like (pseudo code):

    List<Files> directories = new ArrayList<> ();
    if (file is directory) directories.add(file);
    else dowloadFile();
    
    for (File f : directories) {
      cd(f);
      ftpFiles(listFiles());
      cd(..);
    }