所需jar包,及下载地址
jsch:Maven Repository: com.jcraft » jsch » 0.1.55 (mvnrepository.com)文章来源:https://www.toymoban.com/news/detail-515549.html
文章来源地址https://www.toymoban.com/news/detail-515549.html
创建 DownloadDirectoryFromLinux 工具类,用来下载文件
public class DownloadDirectoryFromLinux {
public void main() {
String hostname = "linux的ip地址(10.***.*.***)";
int port = 端口号(22);
String username = "用户名(root)";
String password = "密码";
String remoteDirPath = "linux需要下载的文件目录(/root/test)";
String localDirPath = "保存到本地的文件目录(D:\\Desktop\\test\\)";
JSch jsch = new JSch();
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
try {
session = jsch.getSession(username, hostname, port);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setTimeout(30000);
session.setServerAliveInterval(5000);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp) channel;
channelSftp.cd(remoteDirPath);
Vector<ChannelSftp.LsEntry> files = channelSftp.ls(remoteDirPath);
String[] fileNames = new String[files.size()];
for (int i = 0; i < files.size(); i++) {
fileNames[i] = files.get(i).getFilename();
}
int count = 0;
//遍历remoteDirPath 下的每一个文件
for (String fileName : fileNames) {
count+=1;
if (count>=3){
//如果把remoteDirPath 当作一级目录,那remoteFilePath 就是第二级目录
String remoteFilePath = remoteDirPath + "/" + fileName;
String localFilePath = localDirPath + fileName;
//channelSftp.get()方法不能远程下载目录,
//channelSftp.get(remoteFilePath, localFilePath);
//上面这样会报错,具体可以查看源码
//下面这个方法遍历第二级目录下的所有文件
downloadDirectory(remoteFilePath,localFilePath,channelSftp);
}
}
System.out.println("文件下载完成");
} catch (JSchException | SftpException e) {
e.printStackTrace();
} finally {
if (channelSftp != null) {
channelSftp.disconnect();
}
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}
private static void downloadDirectory(String remoteDirPath, String localDirPath, ChannelSftp sftp) throws SftpException {
Vector<ChannelSftp.LsEntry> files = sftp.ls(remoteDirPath);
for (ChannelSftp.LsEntry file : files) {
String str = file.getFilename().toString();
String type = str.substring(str.lastIndexOf(".") + 1);
//我这里只保存后缀名为svg和xml的文件
if (type.equals("svg") || type.equals("xml")){
if (!file.getAttrs().isDir()) {
File file1 = new File(localDirPath);
if (!file1.exists()){
file1.mkdirs();
}
String linuxFilePath = remoteDirPath + "/" + file.getFilename();
String localFilePath = localDirPath + "\\" + file.getFilename();
//下载文件
sftp.get(linuxFilePath,localFilePath);
} else if (!file.getFilename().equals(".") && !file.getFilename().equals("..")) {
File newDir = new File(localDirPath + "\\" + file.getFilename());
newDir.mkdirs();
downloadDirectory(remoteDirPath + "/" + file.getFilename(), newDir.getAbsolutePath(), sftp);
}
}
}
}
}
到了这里,关于java根据服务器(linux)端ip+文件路径将服务器端文件下载到本地的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!