分享JAVA的FTP和SFTP相关操作工具类
1、导入相关jar
<!--FTPClient-->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.3</version>
</dependency>
<!-- sftp的依赖-->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.51</version>
</dependency>
2、工具类实现代码
package com.shsnc.dbtdemo.common.utils;
import com.alibaba.druid.util.StringUtils;
import com.jcraft.jsch.*;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
/**
* ftp相关工具类
*
* @author klp
* @Date 2022-5-31
*/
public class FtpUtil {
private static final String CHECK_FILE_SUFFIX = ".txt,.csv,.docx,.mp4,.png,.jpg,.xlsx,.log,.json"; //文件验证(datax仅支持text和csv)
private static String host = "172.168.48.59";
private static int port = 21;
private static String username = "1klp321";
private static String password = "121klp3f2@d";
private static String sftpHost = "147.165.185.118";
private static int sftpPort = 0;
private static String sftpUsername = "root";
private static String sftpPassword = "1klp@19dar3";
/**
* ftp创建连接
* @param host 主机IP
* @param port 端口
* @param username 用户名
* @param password 密码
* @return
* @throws IOException
*/
public static FTPClient connectByFtp(String host, int port, String username, String password) throws IOException {
FTPClient ftp = new FTPClient();
//防止中文乱码,不能在connect,login之后设置,查看源码得知
// FTPClient继承FTP,FTP继承SocketClient,
// 所以ftpClient调用方法connect()时,会调用_connectAction_()方法,如果还没有没置编码,
// getControlEncoding()会默认使用ios-8859-1,
// 所以必需在connect前完成编码设置
ftp.setControlEncoding("GBK");
// 设置ip和端口
ftp.connect(host, port);
// 设置用户名和密码
ftp.login(username, password);
// 设置文件类型(二进制传输模式)
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
// 设置被动模式
ftp.enterLocalPassiveMode();
if (ftp.getReplyCode() == 200) {
return ftp;
} else {
System.out.println("ftp连接状态:" + ftp.getReplyCode());
return null;
}
}
/**
* ftp获取全部目录路径
*
* @return
* @throws IOException
*/
public static List<String> getFtpDir() throws IOException {
List<String> fileList = new ArrayList<>();
FTPClient ftpClient = connectByFtp(host, port, username, password);
String dirHome = ftpClient.printWorkingDirectory();
fileList.add(dirHome);
getFtpDirList(ftpClient, fileList, dirHome);
System.out.println("ftp dir list:" + fileList);
ftpClient.logout();
ftpClient.disconnect();
return fileList;
}
/**
* ftp根据目录获取目录下全部文件
*
* @param dir 路径
* @return
* @throws IOException
*/
public static List<String> getFtpList(String dir) throws IOException {
List<String> fileList = null;
FTPClient ftpClient = connectByFtp(host, port, username, password);
fileList = getFtpFileList(ftpClient, dir);
System.out.println("ftp file list:" + fileList);
ftpClient.logout();
ftpClient.disconnect();
return fileList;
}
/**
* ftp递归获取目录列表
*
* @param fileList 文件结合
* @param dir 路径
*/
public static void getFtpDirList(FTPClient ftpClient, List<String> fileList, String dir) {
try {
FTPFile[] files = ftpClient.listFiles(dir);
if (files != null && files.length > 0) {
for (FTPFile file : files) {
if (file.isDirectory()) {
String fileDir = dir.concat("/").concat(file.getName());
fileList.add(fileDir);
getFtpDirList(ftpClient, fileList, fileDir);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* ftp获取目录下的文件
*
* @param dir 路径
* @throws IOException
*/
public static List<String> getFtpFileList(FTPClient ftpClient, String dir) throws IOException {
List<String> fileList = new ArrayList<>();
try {
FTPFile[] files = ftpClient.listFiles(dir);
if (files != null && files.length > 0) {
for (FTPFile file : files) {
String fileName = file.getName();
if (!".".equals(fileName) && !"..".equals(fileName) && !file.isDirectory()) {
String fileNameSuffix = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf("."), fileName.length()) : fileName;
if (CHECK_FILE_SUFFIX.contains(fileNameSuffix)) {
fileList.add(fileName);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return fileList;
}
/**
* 获取ftp文件的内容,返回创建表的列集合
*
* @return
*/
public static List<String> getFtpContent(String dir, String splitStr) throws IOException {
List<String> fileList = new ArrayList<>();
FTPClient ftpClient = connectByFtp(host, port, username, password);
try {
FTPFile[] files = ftpClient.listFiles(dir);
if (files != null && files.length > 0) {
for (FTPFile file : files) {
file.isDirectory();
System.out.println(file.getName());
//获取核心表数据
InputStream inputStream = ftpClient.retrieveFileStream(file.getName());
if (inputStream != null) {
read(inputStream, splitStr);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return fileList;
}
/**
* 创建SFTP连接
*
* @param host 主机ip
* @param username 用户名
* @param password 密码
* @return
* @throws Exception
*/
public static ChannelSftp connectBySftp(String host, String username, String password) throws JSchException {
ChannelSftp sftp = null;
Session sshSession = null;
JSch jsch = new JSch();
sshSession = jsch.getSession(username, host);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
return sftp;
}
/**
* 获取sftp目录
*
* @return
* @throws SftpException
*/
public static List<String> getSftpDirList() throws SftpException, JSchException {
ChannelSftp channelSftp = connectBySftp(sftpHost, sftpUsername, sftpPassword);
String sftpHome = channelSftp.getHome();
List<String> fileList = new ArrayList<>();
fileList.add(sftpHome);
getFileDirWhile(fileList, channelSftp, sftpHome);
System.out.println("home path:" + fileList);
channelSftp.disconnect();
return fileList;
}
/**
* sftp递归获取路径
*
* @param fileList 文件集合
* @param channelSftp sftp对象
* @param dir 路径
* @throws SftpException
*/
public static void getFileDirWhile(List<String> fileList, ChannelSftp channelSftp, String dir) throws SftpException {
Vector<ChannelSftp.LsEntry> vector = channelSftp.ls(dir);
vector.forEach(file -> {
String fileName = file.getFilename();
if (!(".".equals(fileName)) && !("..".equals(fileName)) && file.getAttrs().isDir()) {
String fileDir = dir.concat("/").concat(fileName);
fileList.add(fileDir);
try {
getFileDirWhile(fileList, channelSftp, fileDir);
} catch (SftpException e) {
e.printStackTrace();
}
}
});
}
/**
* 获取sftp目录下所有文件
*
* @param dir 路径
* @return
* @throws SftpException
*/
public static List<String> getSftpFileList(String dir) throws SftpException, JSchException {
ChannelSftp channelSftp = connectBySftp(sftpHost, sftpUsername, sftpPassword);
List<String> fileList = getSftpFileName(channelSftp, dir);
channelSftp.disconnect();
return fileList;
}
/**
* sftp根据目录获取全部过滤文件名文件名
*
* @param channelSftp sftp对象
* @param dir 路径
* @return
* @throws SftpException
*/
public static List<String> getSftpFileName(ChannelSftp channelSftp, String dir) throws SftpException {
List<String> list = new ArrayList<>();
//ls命令获取文件名列表
Vector<ChannelSftp.LsEntry> vector = channelSftp.ls(dir);
vector.forEach(file -> {
//文件名称
String fileName = file.getFilename();
if (!".".equals(fileName) && !"..".equals(fileName) && !file.getAttrs().isDir()) {
String fileNameSuffix = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf("."), fileName.length()) : fileName;
if (CHECK_FILE_SUFFIX.contains(fileNameSuffix)) {
list.add(fileName);
}
}
});
return list;
}
/**
* 读取Sftp内容
*
* @param channelSftp sftp对象
* @param dir 路径
* @param splitStr 分隔符
* @throws SftpException
*/
public void readContent(ChannelSftp channelSftp, String dir, String splitStr) throws SftpException {
List<String> list = new ArrayList<>();
//ls命令获取文件名列表
Vector<ChannelSftp.LsEntry> vector = channelSftp.ls(dir);
vector.forEach(file -> {
//文件名称
String fileName = file.getFilename();
if (!(".".equals(fileName)) && !("..".equals(fileName)) && !file.getAttrs().isDir()) {
list.add(fileName);
try {
InputStream inputStream = channelSftp.get(dir + fileName);
if (inputStream != null) {
read(inputStream, splitStr);
}
} catch (SftpException e) {
e.printStackTrace();
}
}
});
}
/**
* 读取文件第一行,确定多少列,生成建表列
* 读取csv、txt通用
*
* @param inputStream 文件流
* @param splitStr 分隔符
* @return
*/
public static String read(InputStream inputStream, String splitStr) {
StringBuffer sb = new StringBuffer();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));//GBK
String line = null;
if ((line = reader.readLine()) != null) {
int col = line.split(splitStr).length;
}
reader.close();
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws SftpException, IOException, JSchException {
//ftp获取目录和文件
List<String> list = getSftpDirList();
System.out.println(list);
list.forEach(dir -> {
try {
System.out.println(getSftpFileList(dir));
} catch (SftpException | JSchException e) {
e.printStackTrace();
}
});
//ftp获取目录和文件
List<String> listFtp = getFtpDir();
listFtp.forEach(dir -> {
try {
getFtpList(dir);
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
分享JAVA的FTP和SFTP相关操作工具类的更多相关文章
- java通过ftp和sftp上传war包上传到Linux服务器实现自动重启tomcat的脚本代码
ar包自动上传Linux并且自动重启tomcat 用的是jdk1.7出的文件监控 支持ftp和sftp,支持多服务器负载等 配置好config 非maven项目导入直接使用 #\u76D1\u542C ...
- Java实现FTP与SFTP文件上传下载
添加依赖Jsch-0.1.54.jar <!-- https://mvnrepository.com/artifact/com.jcraft/jsch --> <dependency ...
- 文件相关操作工具类——FileUtils.java
文件相关操作的工具类,创建文件.删除文件.删除目录.复制.移动文件.获取文件路径.获取目录下文件个数等,满足大多数系统需求. 源码如下:(点击下载 FileUtils.java) import jav ...
- java并发编程基础——线程相关的类
线程相关类 java还为线程安全提供了一些工具类. 一.ThreadLocal类(Thread Local Variable) ThreadLocal类,是线程局部变量的意思.功用非常简单,就是为每一 ...
- Java基础 与时间日期相关的类:System -Date -SimpleDateFormat -Calendar类 -解决后缀.000Z 的时区问题
笔记总结: /**与时间相关的类:System_Date_SimpleDateFormat_Calendar类 * 1.system 类下的currentTimeMillis() * 输出从1970年 ...
- docker 部署vsftpd服务、验证及java ftp操作工具类
docker部署vsftpd服务 新建ftp文件存储目录/home/ftp cd /home mkdir ftp 创建一个组,用于存放ftp用户 groupadd ftpgroups 创建ftp用户, ...
- Java实现抽奖模块的相关分享
Java实现抽奖模块的相关分享 最近进行的项目中,有个抽奖的需求,今天就把相关代码给大家分享一下. 一.DAO层 /** * 获取奖品列表 * @param systemVersion 手机系统版本( ...
- 170404、java版ftp操作工具类
package com.rick.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotF ...
- FTP、SFTP与FTPS
先简单介绍下FTP的基础知识 FTP的传输有两种方式:ASCII.二进制. FTP支持两种模式:Standard (PORT方式,主动方式),Passive (PASV,被动方式). 主动模式 FTP ...
随机推荐
- PAT B1051 复数乘法
输入样例: 2.3 3.5 5.2 0.4 输出样例: -8.68-8.23i 解题思路: 1.读入R1.P1.R2.P2. 2.A=(R1*R2)cos(P1+P2),B=(R1*R2)sin(P1 ...
- IDEA中 Debug 调试工具(图文详解)
DEBUG调试工具 一. Debug 调试工具 1. Debug的作用 2. Debug的使用步骤 3. IDEA中Debug按钮详解 总结 参考博文:https://blog.csdn.net/qq ...
- 解决vscode开发react项目没有html标签自动补全
怎么设置自动补全: 左下角齿轮按钮--设置-- 在搜索框中输入Include Languages,选择Emmet,并在Emmet:include language下点击在setting.json中编辑 ...
- JS函数传递参数是是按值传递
JavaScript在传参的时候只有一种传递方法那就是按值传递(来自红宝书第四版本) 函数在传递参数的时候会把实参的值拷贝过来一份,而基础类型数据值是存在内存中,在拷贝的时候会复制出来一份,而引用类型 ...
- css3属性之filter初探
filter属性是css不常用的一个属性,但是用好了可以给网页增色不少!ps: IE不支持此属性: img { -webkit-filter: grayscale(100%); /* Chrome, ...
- Python入门-面向对象三大特性-封装
一.封装 封装,顾名思义就是将内容封装到某个地方,以后再去调用被封装在某处的内容. 所以,在使用面向对象的封装特性时,需要: 将内容封装到某处 从某处调用被封装的内容 第一步:将内容封装到某处 sel ...
- 对比学习 ——simsiam 代码解析。
目录 1 : 事先准备 . 2 : 代码阅读. 2.1: 数据读取 2.2: 模型载入 3 训练过程: 4 测试过程: 5 :线性验证 6 : 用自己数据集进行对比学习. 第一: 改数据集 : ...
- IO——字节缓冲流
缓冲流:BufferedInputStream / BufferedOutputStream 提高IO效率,减少访问磁盘的次数 数据存储在缓冲区,调用flush将缓存区的内容写入文件中,也可以直接cl ...
- 合并csv文件保存到一个csv文件中-保留表头
主要实现功能: 在同一文件夹下的所有csv文件全部合并到同一个csv文件中,并将csv文件的表头保留 1 import os 2 import pandas as pd 3 path = os.get ...
- Apache Doris ODBC外表之Postgresql使用指南
Apache Doris 社区 2022 年的总体规划,包括待开展或已开展.以及已完成但需要持续优化的功能.文档.社区建设等多方面,我们期待有更多的小伙伴参与进来讨论.同时也希望多多关注Doris,给 ...