大家好,我正在尝试创建一个小脚本,该脚本可让我通过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实现它。
您必须使用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");
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句