如果是FTP的看这里, 基于java的批量上传下载的FTP工具类
首先引入依赖
<dependency>
<groupId>org.netbeans.external</groupId>
<artifactId>com-jcraft-jsch</artifactId>
<version>RELEASE150</version>
</dependency>
完整代码
package com.salong.myself.test;
import com.jcraft.jsch.*;
import java.io.*;
import java.util.*;
/**
* @author Salong
* @date 2023/1/3 15:09
* @Email:salong0503@aliyun.com
*/
public class SFTPUtil {
private static ChannelSftp sftp = null;
private static Session sshSession = null;
public static void main(String[] args) {
//获取sftp连接
connect("11.22.33.44", 22, "root", "123456");
// //单个文件上传(把本地的test.txt文件上传到远程/salong目录下,并重命名为sa.txt)
uploadFile("/salong","sa.txt","C:\\Users\\86158\\Desktop\\aa1","test.txt");
// //批量文件上传(把本地aa1文件夹下的所有文件(非文件夹)上传到远程/salong/pp2目录下,上传完毕之后删除本地文件)
bacthUploadFile("/salong/pp2","C:\\Users\\86158\\Desktop\\aa1",true);
//单个文件下载,将远程/salong目录下的tst.txt文件下载到本地并重命名为ok.txt
downloadFile("/salong","test.txt","C:\\Users\\86158\\Desktop","ok.txt");
//批量文件下载,不支持二级文件夹的内容下载(远程地址和本地地址必须以分隔符结束,windows是\,linux和unix是/)
batchDownLoadFile("/salong/a/","C:\\Users\\86158\\Desktop\\doc\\","","",false);
disconnect();
}
public static ChannelSftp connect(String sftpHost,int port,String sftpUser,String sftpPwd) {
try {
JSch jsch = new JSch();
jsch.getSession(sftpUser, sftpHost, port);
sshSession = jsch.getSession(sftpUser, sftpHost, port);
sshSession.setPassword(sftpPwd);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect(30000);
Channel channel = sshSession.openChannel("sftp");
channel.connect(10000);
sftp = (ChannelSftp) channel;
System.out.println("连接SFTP服务器成功:"+sftpHost);
return sftp;
} catch (Exception e) {
System.out.println("连接SFTP服务器失败,异常结束"+e.getMessage());
return null;
}
}
/**
* 断开连接
*/
public static void disconnect() {
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
System.out.println("断开连接");
}
}
if (sshSession != null) {
if (sshSession.isConnected()) {
sshSession.disconnect();
System.out.println("会话结束");
}
}
}
/**
* 批量上传文件
* @param remotePath 远程地址
* @param localPath 本地文件路径
* @param del 上传完毕之后是否删除本地文件
* @return
*/
public static boolean bacthUploadFile(String remotePath, String localPath,boolean del) {
try {
File file = new File(localPath);
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()
&& files[i].getName().indexOf("bak") == -1) {
boolean upload = uploadFile(remotePath, files[i].getName(), localPath, files[i].getName());
if (!upload){
return false;
}
if (del) {
//上传后删除本地文件
deleteFile(localPath +File.separator+ files[i].getName());
}
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
disconnect();
}
return false;
}
/**
* 上传单个文件
* @param remotePath:远程保存目录
* @param remoteFileName:保存文件名
* @param localPath:本地上传目录(以路径符号结束)
* @param localFileName:上传的文件名
* @return
*/
public static boolean uploadFile(String remotePath, String remoteFileName,String localPath, String localFileName){
FileInputStream in = null;
try {
createDir(remotePath);
File file = new File(localPath +File.separator+ localFileName);
in = new FileInputStream(file);
sftp.put(in, remoteFileName);
return true;
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (SftpException e){
e.printStackTrace();
}
finally
{
if (in != null){
try{
in.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
return false;
}
public static boolean createDir(String createpath) {
try {
if (isDirExist(createpath)) {
sftp.cd(createpath);
return true;
}
String pathArry[] = createpath.split(File.separator);
StringBuffer filePath = new StringBuffer(File.separator);
for (String path : pathArry) {
if (path.equals("")) {
continue;
}
filePath.append(path + File.separator);
if (isDirExist(filePath.toString())) {
sftp.cd(filePath.toString());
} else {
sftp.mkdir(filePath.toString());
sftp.cd(filePath.toString());
}
}
sftp.cd(createpath);
return true;
} catch (SftpException e) {
e.printStackTrace();
}
return false;
}
public static boolean isDirExist(String directory) {
boolean isDirExistFlag = false;
try {
//lstat()检索文件或目录的文件属性
SftpATTRS sftpATTRS = sftp.lstat(directory);
isDirExistFlag = true;
//isDir()检查此文件是否为目录
return sftpATTRS.isDir();
} catch (Exception e) {
if (e.getMessage().toLowerCase().equals("no such file")) {
isDirExistFlag = false;
}
}
return isDirExistFlag;
}
/**
* 删除stfp文件
* @param directory:要删除文件所在目录
* @param deleteFile:要删除的文件
*/
public static void deleteSFTP(String directory, String deleteFile) {
try {
sftp.rm(directory + deleteFile);
} catch (Exception e) {
System.out.println("删除SFTP文件失败");
}
}
public static boolean deleteFile(String filePath) {
File file = new File(filePath);
if (!file.exists()) {
return false;
}
if (!file.isFile()) {
return false;
}
boolean rs = file.delete();
return rs;
}
/**
* 下载单个文件
* @param directory 下载目录(远程文件所在目录)
* @param downloadFile 下载的文件名
* @param saveFile 结束文件的全路径
* @param sftp
*/
private static void download(String directory, String downloadFile,
String saveFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
sftp.get(downloadFile,saveFile);
}catch (Exception e){
System.out.println("下载sftp文件失败");
}
}
/**
* 下载单个文件
* @param remotePath:远程下载目录(以路径符号结束)
* @param remoteFileName:下载文件名
* @param localPath:本地保存目录(以路径符号结束)
* @param localFileName:保存文件名
* @return
*/
public static boolean downloadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {
FileOutputStream fieloutput = null;
try {
File file = new File(localPath+File.separator + localFileName);
fieloutput = new FileOutputStream(file);
//这里需要注意,如果远端系统是linux或者unix,则文件分隔符是/,如果是windows,则需要手动改为\
String remoteFile = remotePath + "/" + remoteFileName;
sftp.get(remoteFile, fieloutput);
System.out.println("下载成功!");
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
} finally {
if (null != fieloutput) {
try {
fieloutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
/**
* 批量下载文件
* @param remotePath:远程下载目录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/)
* @param localPath:本地保存目录(以路径符号结束,D:\Duansha\sftp\)
* @param fileFormat:下载文件格式(以特定字符开头,为空不做检验)
* @param fileEndFormat:下载文件格式(文件格式)
* @param del:下载后是否删除sftp文件
* @return
*/
public static List<String> batchDownLoadFile(String remotePath, String localPath, String fileFormat, String fileEndFormat, boolean del) {
List<String> filenames = new ArrayList<>();
try {
Vector v = sftp.ls(remotePath); //lstat(String path):列出远程目录的内容
if (v.size() > 0) {
Iterator it = v.iterator();
while (it.hasNext()) {
ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();
String filename = entry.getFilename();
SftpATTRS attrs = entry.getAttrs();
if (!attrs.isDir()) {
boolean flag = false;
String localFileName = localPath + filename;
fileFormat = fileFormat == null ? "" : fileFormat
.trim();
fileEndFormat = fileEndFormat == null ? ""
: fileEndFormat.trim();
// 三种情况
if (fileFormat.length() > 0 && fileEndFormat.length() > 0) {
if (filename.startsWith(fileFormat) && filename.endsWith(fileEndFormat)) {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath, filename);
}
}
}
} else if (fileFormat.length() > 0 && "".equals(fileEndFormat)) {
if (filename.startsWith(fileFormat)) {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath, filename);
}
}
}
} else if (fileEndFormat.length() > 0 && "".equals(fileFormat)) {
if (filename.endsWith(fileEndFormat)) {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath, filename);
}
}
}
} else {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath, filename);
}
}
}
}
}
}
} catch (SftpException e) {
e.printStackTrace();
} finally {
}
return filenames;
}
}