Copy all files with specific extension from remote server with Java

亡梦爱人 提交于 2019-12-13 04:39:39

问题


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.


回答1:


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"); 

        }
    }


来源:https://stackoverflow.com/questions/18831238/copy-all-files-with-specific-extension-from-remote-server-with-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!