Question

Hey everybody I'm trying to create a small script that will let me copy all files with a specific extension from a remote linux machine to my local machine through sftp.

This is the code I have so far, which lets me copy one file from the remote machine to my local machine, using Jsch, if I give the full path.

package transfer;

import com.jcraft.jsch.*;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Scanner;

public class CopyFromServer {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Please enter the hostname or ip of the server on which the ctk files can be found: ");
        String hostname = sc.nextLine();
        System.out.println("Please enter your username: ");
        String username = sc.nextLine();
        System.out.println("Please enter your password: ");
        String password = sc.nextLine();
        System.out.println("Please enter the location where your files can be found: ");
        String copyFrom = sc.nextLine();
        System.out.println("Please enter the location where you want to place your files: ");
        String copyTo = sc.nextLine();

        JSch jsch = new JSch();
        Session session = null;
        try {
            session = jsch.getSession(username, hostname, 22);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(password);
            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftpChannel = (ChannelSftp) channel;

            sftpChannel.get(copyFrom, copyTo);
            sftpChannel.exit();
            session.disconnect();
        } catch (JSchException e) {
            e.printStackTrace();  
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }
}

I'd like all of the files that have the extension ".jpg" in a specific folder to be copied and place in a folder the user defines.

I've tried:

sftpChannel.get(copyFrom + "*.jpg", copyTo);

Which did not work, I know I should use something like:

pathname.getName().endsWith("." + fileType)

But I'm not sure how to implement it with sftpChannel.

Was it helpful?

Solution

You have to use sftpChannel.ls("Path to dir"); which will returns list of files in the given path as a vector and you have to iterate on the vector to download each file sftpChannel.get();

Vector<ChannelSftp.LsEntry> list = sftpChannel .ls("."); 
    // iterate through objects in list, and check for extension
    for (ChannelSftp.LsEntry listEntry : list) {
            sftpChannel.get(listEntry.getFilename(), "fileName"); 

        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top