一、添加maven依赖
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.7.2</version>
</dependency>
二、主要代码块
package com.eurekaclient.utils;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.util.Properties;
@Slf4j
public class FtpUtils {
private static final String ftpIp = "127.0.0.1";
private static final String ftpPort = "22";
private static final String ftpUserName = "admin";
private static final String ftpPassWord = "admin";
private static final String timeout = "6000";
private static ChannelSftp channelSftp = null;
private static Session session = null;
private static Channel channel = null;
public static boolean isOpen() {
try {
channelSftp = new ChannelSftp();
channelSftp.getServerVersion();
return true;
} catch (Exception e) {
log.error("{}", e.getMessage());
return false;
}
}
public static void connectionFtp() {
try {
boolean open = isOpen();
if (!open) {
JSch jsch = new JSch();
session = jsch.getSession(ftpUserName, ftpIp, Integer.parseInt(ftpPort));
session.setPassword(ftpPassWord);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setTimeout(Integer.parseInt(timeout));
session.connect();
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp) channel;
}
} catch (Exception e) {
log.error("{}", e.getMessage());
}
}
public static void uploadImage(String uploadPath, String localPath) {
FileInputStream io = null;
try {
log.info("上传图片starting");
connectionFtp();
if (null == channelSftp || channelSftp.isClosed()) {
log.error("链接丢失");
}
if (isExistDir(uploadPath)) {
channelSftp.cd(uploadPath);
} else {
createDir(uploadPath, channelSftp);
}
File file = new File(localPath);
io = new FileInputStream(file);
channelSftp.put(io, file.getName());
log.info("上传图片ending");
} catch (Exception e) {
log.error("{}", e.getMessage());
} finally {
if (null != io) {
try {
io.close();
} catch (IOException e) {
e.printStackTrace();
}
}
disconnect();
}
}
public static void downLoad(String downloadPath, String localPath) {
FileOutputStream out = null;
try {
log.info("下载图片starting");
connectionFtp();
if (null == channelSftp || channelSftp.isClosed()) {
log.error("链接丢失");
}
String[] pathArry = downloadPath.split("/");
StringBuffer filePath = new StringBuffer("/");
for (int i = 0; i < pathArry.length - 1; i++) {
if ("".equals(pathArry[i])) {
continue;
}
filePath.append(pathArry[i]).append("/");
}
channelSftp.cd(filePath.toString());
log.info("当前目录为:{}", channelSftp.pwd());
File files = new File(localPath);
if (!files.exists()) {
boolean mkdirs = files.mkdirs();
log.info("创建目录:{}", mkdirs);
}
if (!files.canWrite()) {
if (!files.setWritable(true)) {
throw new FileNotFoundException();
}
}
String fileName = pathArry[pathArry.length - 1];
File file = new File(localPath + fileName);
out = new FileOutputStream(file);
channelSftp.get(downloadPath, out);
} catch (Exception e) {
log.error("{}", e.getMessage());
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
log.error("{}", e.getMessage());
}
}
disconnect();
}
}
public static void disconnect() {
if (channelSftp.isConnected()) {
session.disconnect();
channelSftp.disconnect();
}
}
public static boolean isExistDir(String directory) {
boolean isDirExistFlag = false;
try {
SftpATTRS sftpAttrS = channelSftp.lstat(directory);
isDirExistFlag = true;
return sftpAttrS.isDir();
} catch (Exception e) {
if ("no such file".equals(e.getMessage().toLowerCase())) {
isDirExistFlag = false;
}
}
return isDirExistFlag;
}
public static void createDir(String createpath, ChannelSftp sftp) throws Exception {
try {
String[] pathArry = createpath.split("/");
StringBuffer filePath = new StringBuffer("/");
for (String path : pathArry) {
if ("".equals(path)) {
continue;
}
filePath.append(path).append("/");
if (isExistDir(filePath.toString())) {
sftp.cd(filePath.toString());
} else {
sftp.mkdir(filePath.toString());
sftp.cd(filePath.toString());
}
}
channelSftp.cd(createpath);
} catch (SftpException e) {
log.error("创建目录失败,{}", e.getMessage());
}
}
}
三、测试类
package com.eurekaclient.controller;
import com.eurekaclient.utils.FtpUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class FtpController {
public static void main(String[] args) {
try {
FtpUtils.uploadImage("/vsftp/data/test/", "D:\\images\\063c6aa05dfa49acb705f928f5e5f3a8.jpg");
FtpUtils.downLoad("/vsftp/data/test/063c6aa05dfa49acb705f928f5e5f3a8.jpg", "D:\\images\\");
} catch (Exception e) {
log.info("{}", e.getMessage());
}
}
}
