Java使用Sftp和Ftp实现对文件的上传和下载

网友投稿 253 2023-01-24

Java使用Sftp和Ftp实现对文件的上传和下载

sftp和ftp两种方式区别,还不清楚的,请自行百度查询,此处不多赘述。完整代码地址在结尾!!

第一步,导入maven依赖

commons-net

commons-net

3.6

com.jcraft

jsch

0.1.55

commons-io

commons-io

2.6

第二步,创建并编写SftpUtils类,运行main方法查看效果,如下

import com.jcraft.jsch.*;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.io.IOUtils;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.util.Properties;

import java.util.Vector;

/**

* @Description: sftp上传下载工具类

* @Author: jinhaoxun

* @Date: 2020/1/16 16:13

* @Version: 1.0.0

*/

@Slf4j

public class SftpUtils {

public static void main(String[] args) throws Exception {

log.info("测试开始!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");

// 1

File file = new File("E:\\2.xlsx");

InputStream inputStream = new FileInputStream(file);

SftpUtils.uploadFile("", "", "", 22, "/usr/local",

"/testfile/", "test.xlsx", null, inputStream);

// 2

SftpUtils.downloadFile("", "", "", 22,null,

"/usr/local/testfile/", "test.csv","/Users/ao/Desktop/test.csv");

// 3

SftpUtils.deleteFile("", "", "", 22,null,

"/usr/local/testfile/", "test.xlsx");

// 4

Vector> fileList = SftpUtils.getFileList("", "", "",

22, null,"/usr/local/testfile/");

log.info(fileList.toString());

log.info("测试结束!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");

}

/**

* @Author: jinhaoxun

* @Description: 下载文件

* @param userName 用户名

* @param password 密码

* @param host http://ip

* @param port 端口

* @param basePath 根路径

* @param filePath 文件路径(加上根路径)

* @param filename 文件名

* @param privateKey 秘钥

* @param input 文件流

* @Date: 2020/1/16 21:23

* @Return: void

* @Throws: Exception

*/

public static void uploadFile(String userName, String password, String host, int port, String basePath,

String filePath, String filename, String privateKey, InputStream input) throws Exception {

Session session = null;

ChannelSftp sftp = null;

// 连接sftp服务器

try {

JSch jsch = new JSch();

if (privateKey != null) {

// 设置私钥

jsch.addIdentity(privateKey);

}

session = jsch.getSession(userName, host, port);

if (password != null) {

session.setPassword(password);

}

Properties config = new Properties();

config.put("StrictHostKeyChecking", "no");

session.setConfig(config);

session.connect();

Channel channel = session.openChannel("sftp");

channel.connect();

sftp = (ChannelSftp) channel;

} catch (JSchException e) {

e.printStackTrace();

}

// 将输入流的数据上传到sftp作为文件

try {

sftp.cd(basePath);

sftp.cd(filePath);

} catch (SftpException e) {

//目录不存在,则创建文件夹

String [] dirs=filePath.split("/");

String tempPath=basePath;

for(String dir:dirs){

if(null== dir || "".equals(dir)){

continue;

}

tempPath+="/"+dir;

try{

sftp.cd(tempPath);

}catch(SftpException ex){

sftp.mkdir(tempPath);

sftp.cd(tempPath);

}

}

}

//上传文件

sftp.put(input, filename);

//关闭连接 server

if (sftp != null) {

if (sftp.isConnected()) {

sftp.disconnect();

}

}

//关闭连接 server

if (session != null) {

if (session.isConnected()) {

session.disconnect();

}

}

}

/**

* @Author: jinhaoxun

* @Description: 下载文件

* @param userName 用户名

* @param password 密码

* @param host ip

* @param port 端口

* @param privateKey 秘钥

* @param directory 文件路径

* @param downloadFile 文件名

* @param saveFile 存在本地的路径

* @Date: 2020/1/16 21:22

* @Return: void

* @Throws: Exception

*/

public static void downloadFile(String userName, String password, String host, int port, String privateKey, String directory,

String downloadFile, String saveFile) throws Exception{

Session session = null;

ChannelSftp sftp = null;

// 连接sftp服务器

try {

JSch jsch = new JSch();

if (privateKey != null) {

// 设置私钥

jsch.addIdentity(privateKey);

}

session = jsch.getSession(userName, host, port);

if (password != null) {

session.setPassword(password);

}

Properties config = new Properties();

config.put("StrictHostKeyChecking", "no");

session.setConfig(config);

session.connect();

Channel channel = session.openChannel("sftp");

channel.connect();

sftp = (ChannelSftp) channel;

} catch (JSchException e) {

e.printStackTrace();

}

if (directory != null && !"".equals(directory)) {

sftp.cd(directory);

}

File file = new File(saveFile);

sftp.get(downloadFile, new FileOutputStream(file));

}

/**

* @Author: jinhaoxun

* @Description: 下载文件

* @param userName 用户名

* @param password 密码

* @param host ip

* @param port 端口

* @param privateKey 秘钥

* @param directory 文件路径

* @param downloadFile 文件名

* @Date: 2020/1/16 21:21

* @Return: byte[]

* @Throws: Exception

*/

public static byte[] downloadFile(String userName, String password, String host, int port, String privateKey,

String directory, String downloadFile) throws Exception{

Session session = null;

ChannelSftp sftp = null;

// 连接sftp服务器

try {

JSch jsch = new JSch();

if (privateKey != null) {

// 设置私钥

jsch.addIdentity(privateKey);

}

session = jsch.getSession(userName, host, port);

if (password != null) {

session.setPassword(password);

}

Properties config = new Properties();

config.put("StrictHostKeyChecking", "no");

session.setConfig(config);

session.connect();

Channel channel = session.openChannel("sftp");

channel.connect();

sftp = (ChannelSftp) channel;

} catch (JSchException e) {

e.printStackTrace();

}

if (directory != null && !"".equals(directory)) {

sftp.cd(directory);

}

InputStream is = sftp.get(downloadFile);

byte[] fileData = IOUtils.toByteArray(is);

return fileData;

}

/**

* @Author: jinhaoxun

* @Description: 删除文件

* @param userName 用户名

* @param password 密码

* @param host ip

* @param port 端口

* @param privateKey 秘钥

* @param directory 文件路径

* @param deleteFile 文件名

* @Date: 2020/1/16 21:24

* @Return: void

* @Throws: Exception

*/

public static void deleteFile(String userName, String password, String host, int port, String privateKey,

String directory, String deleteFile) throws Exception{

Session session = null;

ChannelSftp sftp = null;

// 连接sftp服务器

try {

JSch jsch = new JSch();

if (privateKey != null) {

// 设置私钥

jsch.addIdentity(privateKey);

}

session = jsch.getSession(userName, host, port);

if (password != null) {

session.setPassword(password);

}

Properties config = new Properties();

config.put("StrictHostKeyChecking", "no");

session.setConfig(config);

session.connect();

Channel channel = session.openChannel("sftp");

channel.connect();

sftp http://= (ChannelSftp) channel;

} catch (JSchException e) {

e.printStackTrace();

}

sftp.cd(directory);

sftp.rm(deleteFile);

}

/**

* @Author: jinhaoxun

* @Description: 列出目录下的文件

* @param userName 用户名

* @param password 密码

* @param host ip

* @param port 端口

* @param privateKey 秘钥

* @param directory 要列出的目录

* @Date: 2020/1/16 21:25

* @Return: java.util.Vector>

* @Throws: Exception

*/

public static Vector> getFileList(String userName, String password, String host, int port, String privateKey,

http:// String directory) throws Exception {

Session session = null;

ChannelSftp sftp = null;

// 连接sftp服务器

try {

JSch jsch = new JSch();

if (privateKey != null) {

// 设置私钥

jsch.addIdentity(privateKey);

}

session = jsch.getSession(userName, host, port);

if (password != null) {

session.setPassword(password);

}

Properties config = new Properties();

config.put("StrictHostKeyChecking", "no");

session.setConfig(config);

session.connect();

Channel channel = session.openChannel("sftp");

channel.connect();

sftp = (ChannelSftp) channel;

} catch (JSchException e) {

e.printStackTrace();

}

return sftp.ls(directory);

}

}

第三步,创建并编写FtpUtils类,运行main方法查看效果,如下

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.net.ftp.FTP;

import org.apache.commons.net.ftp.FTPClient;

import org.apache.commons.net.ftp.FTPFile;

import org.apache.commons.net.ftp.FTPReply;

import java.io.*;

/**

* @Description: ftp上传下载工具类

* @Author: jinhaoxun

* @Date: 2020/1/16 15:46

* @Version: 1.0.0

*/

@Slf4j

public class FtpUtils {

public static void main(String[] args) throws Exception {

log.info("测试开始!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");

// 1

File file = new File("E:\\2.xlsx");

InputStream inputStream = new FileInputStream(file);

FtpUtils.uploadFile("", 21, "", "", "/usr/local",

"/testfile/", "test.xlsx", inputStream);

// 2

FtpUtils.downloadFile("", 21, "", "","/usr/local/testfile/",

"test.csv", "/Users/ao/Desktop/test.csv");

log.info("测试结束!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");

}

/**

* @Author: jinhaoxun

* @Description: 向FTP服务器上传文件

* @param host FTP服务器hostname

* @param port FTP服务器端口

* @param userName FTP登录账号

* @param password FTP登录密码

* @param basePath FTP服务器基础目录

* @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath

* @param filename 上传到FTP服务器上的文件名

* @param input 本地要上传的文件的 输入流

* @Date: 2020/1/16 19:31

* @Return: boolean

* @Throws: Exception

*/

public static boolean uploadFile(String host, int port, String userName, String password, String basePath,

String filePath, String filename, InputStream input) throws Exception{

boolean result = false;

FTPClient ftp = new FTPClient();

try {

int reply;

// 连接FTP服务器

ftp.connect(host, port);

// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器

// 登录

ftp.login(userName, password);

reply = ftp.getReplyCode();

if (!FTPReply.isPositiveCompletion(reply)) {

ftp.disconnect();

return result;

}

//切换到上传目录

if (!ftp.changeWorkingDirectory(basePath+filePath)) {

//如果目录不存在创建目录

String[] dirs = filePath.split("/");

String tempPath = basePath;

for (String dir : dirs) {

if (null == dir || "".equals(dir)){

continue;

}

tempPath += "/" + dir;

if (!ftp.changeWorkingDirectory(tempPath)) {

if (!ftp.makeDirectory(tempPath)) {

return result;

} else {

ftp.changeWorkingDirectory(tempPath);

}

}

}

}

//设置上传文件的类型为二进制类型

ftp.setFileType(FTP.BINARY_FILE_TYPE);

//上传文件

if (!ftp.storeFile(filename, input)) {

return result;

}

input.close();

ftp.logout();

result = true;

} catch (IOException e) {

e.printStackTrace();

} finally {

if (ftp.isConnected()) {

try {

ftp.disconnect();

} catch (IOException ioe) {

}

}

}

return result;

}

/**

* @Author: jinhaoxun

* @Description: 从FTP服务器下载文件

* @param host FTP服务器hostname

* @param port FTP服务器端口

* @param userName FTP登录账号

* @param password FTP登录密码

* @param remotePath FTP服务器上的相对路径

* @param fileName 要下载的文件名

* @param localPath 下载后保存到本地的路径

* @Date: 2020/1/16 19:34

* @Return: boolean

* @Throws: Exception

*/

public static boolean downloadFile(String host, int port, String userName, String password, String remotePath,

String fileName, String localPath) throws Exception {

boolean result = false;

FTPClient ftp = new FTPClient();

try {

int reply;

ftp.connect(host, port);

// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器

// 登录

ftp.login(userName, password);

reply = ftp.getReplyCode();

if (!FTPReply.isPositiveCompletion(reply)) {

ftp.disconnect();

return result;

}

// 转移到FTP服务器目录

ftp.changeWorkingDirectory(remotePath);

FTPFile[] fs = ftp.listFiles();

for (FTPFile ff : fs) {

if (ff.getName().equals(fileName)) {

java.io.File localFile = new File(localPath + "/" + ff.getName());

OutputStream is = new FileOutputStream(localFile);

ftp.retrieveFile(ff.getName(), is);

is.close();

}

}

ftp.logout();

result = true;

} catch (IOException e) {

e.printStackTrace();

} finally {

if (ftp.isConnected()) {

try {

ftp.disconnect();

} catch (IOException ioe) {

}

}

}

return result;

}

}

完整代码地址:https://github.com/luoyusoft/java-demo

注:此工程包含多个包,FtpUtils代码均在com.luoyu.java.ftp包下

注:此工程包含多个包,SftpUtils代码均在com.luoyu.java.sftp包下

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Intellij IDEA连接Navicat数据库的方法
下一篇:腾讯地图开放api接口(腾讯地图api开放平台)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~