引入pom
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.46</version> <!-- 请根据实际情况检查最新版本 -->
</dependency>
import com.jcraft.jsch.*;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
/**
* @author mujiechen
* @description 两台服务器之间的文件上传于下载工具类
* @date 2024/8/1 9:27
* <p>
* File 类
* public boolean exists() true:文件夹或者文件存在 ,false:文件夹或者文件不存在
* public boolean isFile() true:表示为文件 ,false:表示不是文件
* public boolean isDirectory() true: 表示为文件夹 ,false:表示不是文件夹
**/
public class FileUtil {
/**
* linux服务器的ip
*/
private String host;
/**
* 端口号:一般为22
*/
private int port;
/**
* 私钥:可以不存在
*/
private String privateKey;
/**
* 登录名称
*/
private String username;
/**
* 登录密码
*/
private String password;
/**
* 文件传输通道
*/
private ChannelSftp sftp;
public FileUtil(String username, String password, String host, int port) {
this.username = username;
this.password = password;
this.host = host;
this.port = port;
setChannel();
}
public FileUtil(String username, String host, int port, String privateKey) {
this.username = username;
this.host = host;
this.port = port;
this.privateKey = privateKey;
setChannel();
}
/**
* 检查并设置传输文件的通道
*/
private void setChannel() {
try {
JSch jSch = new JSch();
if (privateKey != null) {
jSch.addIdentity(privateKey);
}
Session session = jSch.getSession(username, host, port);
if (password != null) {
session.setPassword(password);
}
session.setTimeout(100000);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
this.sftp = (ChannelSftp) channel;
System.out.println("登录成功!");
} catch (JSchException e) {
System.out.println("登录失败!");
e.printStackTrace();
}
}
/**
* 本地文件上传到linux系统
* 需要保存到sftp系统上面的文件路径,文件名称,文件流,流操作结束后,需要自己进行关闭输入流(流不是方法本身创建的,则不能够在方法内部关闭),避免出现问题
*
* @param savePath 保存文件的路径
* @param sftpFileName 保存的文件名称
* @param inputStream 本地文件输入流
*/
public void upload(String savePath, String sftpFileName, InputStream inputStream) throws SftpException {
//进入到需要保存文件目录
sftp.cd(savePath);
sftp.put(inputStream, sftpFileName);
System.out.println("上传成功");
}
/**
* 适用于:从linux文件中拷贝文件到本地系统中,自己进行创建流
*
* @param uploadPath 需要拷贝本地文件的全路径
* @param saveDirectory 保存文件到服务器目录的路径
*/
public void upload(String uploadPath, String saveDirectory) throws Exception {
//判定文件是否存在,不存在或者不是文件抛出异常
File file = new File(uploadPath);
if (!file.exists() || !file.isFile()) {
throw new Exception(uploadPath + ":上传路径不存在,或者不是文件");
}
String fileName = file.getName();
InputStream is = new FileInputStream(file);
//进入到上传保存目录
sftp.cd(saveDirectory);
//进行io操作
sftp.put(is, fileName);
//关闭io流
is.close();
System.out.println("上传成功");
}
/**
* 从服务器下载文件到本地
*
* @param directory 下载的文件绝对路径 例如:/root/images/
* @param downloadFile 下载的文件名 1.txt
* @param saveFileDirectory 保存的文件路径
*/
public void download(String directory, String downloadFile, String saveFileDirectory) throws SftpException, IOException {
String saveFile = saveFileDirectory + "\\" + downloadFile;
if (StringUtils.isNotBlank(directory)) {
downloadFile = directory + "/" + downloadFile;
}
File file = new File(saveFile);
FileOutputStream stream = new FileOutputStream(file);
sftp.get(directory, stream);
stream.close();
System.out.println("下载成功");
}
/**
* 通过流的方式下载文件
* @param directory
* @param response
* @throws SftpException
* @throws IOException
*/
public void downloadByOs(String directory, HttpServletResponse response) throws SftpException, IOException {
// 打开远程文件的输入流
InputStream inputStream = sftp.get(directory);
OutputStream outputStream=response.getOutputStream();
// 将输入流的内容写入前端的输出流
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
// 关闭输入流和输出流
inputStream.close();
outputStream.close();
}
/**
* 获取文件夹下面的所有文件
* @param fileFolder
* @return
* @throws SftpException
*/
public List<Map<String,Object>> getFileName(String fileFolder) throws Exception {
List<Map<String,Object>> stringList=new ArrayList<>();
sftp.cd(fileFolder);
listAllFilesAndDirectories( fileFolder,stringList);
System.out.println(stringList.toString());
return stringList;
}
public void listAllFilesAndDirectories( String path ,List<Map<String,Object>> stringList) throws Exception {
Vector<ChannelSftp.LsEntry> list = sftp.ls(path);
for (ChannelSftp.LsEntry entry : list) {
String filename = entry.getFilename();
if(filename.equals(".")){
continue;
}
if(filename.equals("..")){
continue;
}
String filePath = path + "/" + filename;
if (entry.getAttrs().isDir()) {
listAllFilesAndDirectories(filePath,stringList);
} else {
Map<String,Object> map=new HashMap<>();
map.put("filename",filename);
map.put("filePath",filePath);
stringList.add(map);
System.out.println(filePath);
}
}
}
/**
* 测试上传和下载
*/
public static void main(String[] args) throws Exception {
FileUtil fiel = new FileUtil("服务器账号", "服务器密码", "服务器ip", 22);
fiel.getFileName("服务器文件夹绝对路径");
//测试上传功能
// File file = new File("/home/hncht-admin/backmysql");
// InputStream is = new FileInputStream(file);
fiel.upload("/root/images", "owl.png", is);
// is.close();
//测试下载功能
// fiel.download("/root/images", "owl.png", "D:\\image");
}
}