使用Java从远程服务器复制具有特定扩展名的所有文件

时间:2013-09-16 15:01:57

标签: java jsch

嘿大家我正在尝试创建一个小脚本,让我通过sftp将具有特定扩展名的所有文件从远程linux机器复制到我的本地机器。

这是我到目前为止的代码,它允许我使用Jsch将一个文件从远程计算机复制到本地计算机,如果我给出完整路径。

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();
        }
    }
}

我希望复制特定文件夹中包含扩展名“.jpg”的所有文件,并将其放在用户定义的文件夹中。

我试过了:

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

哪个不起作用,我知道我应该使用类似的东西:

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

但我不确定如何使用sftpChannel实现它。

1 个答案:

答案 0 :(得分:2)

您必须使用sftpChannel.ls("Path to dir");,它将返回给定路径中的文件列表作为向量,您必须迭代向量以下载每个文件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"); 

        }
    }