1. Add maven dependency
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.7.2</version>
</dependency>
1
2
3
4
5
2. Main Code block
package com.eurekaclient.utils;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.util.Properties;
@Slf4j
public class FtpUtils {
/**
* ftp address
*/
private static final String ftpIp = "127.0.0.1";
/**
* ftp port
*/
private static final String ftpPort = "22";
/**
* ftp account
*/
private static final String ftpUserName = "admin";
/**
* ftp password
*/
private static final String ftpPassWord = "admin";
/**
* timeout time
*/
private static final String timeout = "6000";
/**
* sftp object
*/
private static ChannelSftp channelSftp = null;
/**
* session
*/
private static Session session = null;
/**
* 通道
*/
private static Channel channel = null;
/**
* Determine whether ftp is connected
*
* @return
*/
public static boolean isOpen() { try { channelSftp = new ChannelSftp(); channelSftp.getServerVersion(); return true; } catch (Exception e) { log.error ("{}", e. getMessage()); return false; }
}
/**
* ftp link
*/
public static void connectionFtp() { try { boolean open = isOpen(); if (!open) { // create JSch object JSch jsch = new JSch(); // pass username, host Address, port get a Session object session = jsch.getSession(ftpUserName, ftpIp, Integer.parseInt(ftpPort)); session.setPassword(ftpPassWord);
// Set properties for the Session object
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
// Set the timeout
session.setTimeout(Integer.parseInt(timeout) );
// Establish a connection
session.connect();
// Open an SFTP channel
channel = session.openChannel("sftp");
// Establish a connection for an SFTP channel
channel.connect();
channelSftp = (ChannelSftp) channel;
}
} catch (Exception e) { log. error("{}", e.getMessage());
}
}
/**
* @param uploadPath upload file address
* @param localPath local file address
*/
public static void uploadImage(String uploadPath, String localPath) { FileInputStream io = null; try { log.info("upload image starting"); connectionFtp (); if (null == channelSftp || channelSftp.isClosed()) { log.error("Link lost"); } 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();
}
}
/**
* @param downloadPath download file address
* @param localPath local file address
*/
public static void downLoad(String downloadPath, String localPath) { FileOutputStream out = null; try { log.info("download picture starting"); connectionFtp (); if (null == channelSftp || channelSftp.isClosed()) { log.error("Link lost"); } 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("The current directory is: {}", channelSftp.pwd() );
//Judge whether there is a local directory
File files = new File(localPath);
if (!files.exists()) { boolean mkdirs = files.mkdirs(); log.info("Create directory: {}", mkdirs ); } // writable 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();
}
}
/**
* 关闭ftp
*/
public static void disconnect() {
if (channelSftp.isConnected()) {
session.disconnect();
channelSftp.disconnect();
}
}
/**
* Determine whether a directory exists and create a directory
*/
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; }
/**
* @param createpath 文件目录地址
*/
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());
// enter and set as the current directory
sftp.cd(filePath.toString());
}
}
channelSftp.cd(createpath);
} catch (SftpException e) { log.error( "Failed to create directory, {}", e.getMessage()); } } } Third, test class 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());
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
—————————————————
Copyright statement: This article is an original article of CSDN blogger "Weiwei~", and follows the CC 4.0 BY-SA copyright agreement. For reprinting, please attach the original source link and this article statement.
Original link: https://blog.csdn.net/weixin_42906244/article/details/126406329