java中实现ftp文件下载
1.maven 引用相关依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.6.7</version>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.5</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
2.对应代码示例
实现类
public class SftpDemo {
private static String username = "账号";
private static String password = "密码";
private static String ip = "自己的ip";
private static int port = 22;
public static void main(String[] args) {
SftpUtil sftpUtil = new SftpUtil(username, password, ip, port);
sftpUtil.login();
sftpUtil.download("/app/source/Test", "demo.txt", "E:\\Test\\demo1.txt");
sftpUtil.logout();
}
}
工具类 SftpUtil
package com.lx.util;
import cn.hutool.log.StaticLog;
import com.jcraft.jsch.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.*;
import java.util.Vector;
public class SftpUtil {
private ChannelSftp sftp;
private Session session;
private String username;
private String password;
private String privateKey;
private String host;
private int port;
public SftpUtil(String username, String password, String host, int port) {
this.username = username;
this.password = password;
this.host = host;
this.port = port;
}
public SftpUtil(String username, String privateKey, int port, String host) {
this.username = username;
this.privateKey = privateKey;
this.host = host;
this.port = port;
}
public void login() {
JSch jsch = new JSch();
try {
if (privateKey != null) {
jsch.addIdentity(privateKey);
}
session = jsch.getSession(username, host, port);
if (password != null) {
session.setPassword(password);
}
session.setConfig("PreferredAuthentications", "password");
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
StaticLog.info("sftp server connect success !!");
} catch (JSchException e) {
StaticLog.error("SFTP服务器连接异常!!", e);
}
}
public void logout() {
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
StaticLog.info("sftp is close already");
}
}
if (session != null) {
if (session.isConnected()) {
session.disconnect();
StaticLog.info("session is close already");
}
}
}
public void upload(String directory, String sftpFileName, InputStream input) throws SftpException {
long start = System.currentTimeMillis();
try {
if (sftp.ls(directory) == null) {
sftp.mkdir(directory);
}
sftp.cd(directory);
} catch (SftpException e) {
sftp.mkdir(directory);
sftp.cd(directory);
}
sftp.put(input, sftpFileName);
StaticLog.info("文件上传成功!!");
}
public void upload(String directory, String uploadFileUrl) {
File file = new File(uploadFileUrl);
try {
upload(directory, file.getName(), new FileInputStream(file));
} catch (SftpException e) {
StaticLog.error("上传文件异常!", e);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void upload(String directory, String sftpFileName, byte[] bytes) {
try {
upload(directory, sftpFileName, new ByteArrayInputStream(bytes));
} catch (SftpException e) {
StaticLog.error("上传文件异常!", e);
}
}
public void upload(String directory, String sftpFileName, String dataStr, String charsetName) {
try {
upload(directory, sftpFileName, new ByteArrayInputStream(dataStr.getBytes(charsetName)));
} catch ( SftpException e) {
StaticLog.error("上传文件异常!", e);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public void download(String directory, String downloadFile, String saveFile) {
try {
if (directory != null && !"".equals(directory)) {
sftp.cd(directory);
}
File file = new File(saveFile);
sftp.get(downloadFile, new FileOutputStream(file));
StaticLog.info("文件下载成功");
} catch (FileNotFoundException e) {
StaticLog.error("文件下载异常!", e);
StaticLog.error(e);
} catch (SftpException e) {
e.printStackTrace();
}
}
public byte[] download(String directory, String downloadFile) {
try {
if (directory != null && !"".equals(directory)) {
sftp.cd(directory);
}
InputStream inputStream = sftp.get(downloadFile);
return IOUtils.toByteArray(inputStream);
} catch (IOException e) {
StaticLog.error("文件下载异常!", e);
} catch (SftpException e) {
e.printStackTrace();
}
return null;
}
public InputStream downloadStream(String directory, String downloadFile) {
try {
if (directory != null && !"".equals(directory)) {
sftp.cd(directory);
}
return sftp.get(downloadFile);
} catch (SftpException e) {
StaticLog.error("文件下载异常!", e);
}
return null;
}
public void delete(String directory, String deleteFileName) {
try {
sftp.cd(directory);
sftp.rm(deleteFileName);
} catch (SftpException e) {
StaticLog.error("文件删除异常!", e);
}
}
public void delete(String directory) {
Vector vector = listFiles(directory);
vector.remove(0);
vector.remove(0);
for (Object v : vector) {
ChannelSftp.LsEntry lsEntry = (ChannelSftp.LsEntry) v;
try {
sftp.cd(directory);
sftp.rm(lsEntry.getFilename());
} catch (SftpException e) {
StaticLog.error("文件删除异常!", e);
}
}
}
public Vector<?> listFiles(String directory) {
try {
if (isDirExist(directory)) {
Vector<?> vector = sftp.ls(directory);
vector.remove(0);
vector.remove(0);
return vector;
}
} catch (SftpException e) {
StaticLog.info("获取文件夹信息异常!", e);
}
return null;
}
public boolean booleanUrl(String directory) {
try {
if (sftp.ls(directory) == null) {
return false;
}
} catch (Exception e) {
StaticLog.error("检测文件夹异常!", e);
}
return true;
}
public boolean createDir(String createpath) {
try {
if (isDirExist(createpath)) {
this.sftp.cd(createpath);
return true;
}
String pathArry[] = createpath.split("/");
StringBuffer filePath = new StringBuffer("/");
for (String path : pathArry) {
if (path.equals("")) {
continue;
}
filePath.append(path + "/");
if (isDirExist(filePath.toString())) {
sftp.cd(filePath.toString());
} else {
sftp.mkdir(filePath.toString());
sftp.cd(filePath.toString());
}
}
this.sftp.cd(createpath);
} catch (SftpException e) {
StaticLog.error("目录创建异常!", e);
return false;
}
return true;
}
public boolean isDirExist(String directory) {
boolean isDirExistFlag = false;
try {
SftpATTRS sftpATTRS = this.sftp.lstat(directory);
isDirExistFlag = true;
return sftpATTRS.isDir();
} catch (Exception e) {
if (e.getMessage().toLowerCase().equals("no such file")) {
isDirExistFlag = false;
}
}
return isDirExistFlag;
}
public void mkdirs(String path) {
File file = new File(path);
String fs = file.getParent();
file = new File(fs);
if (!file.exists()) {
file.mkdirs();
}
}
public boolean isExist(String path, ChannelSftp sftp) {
boolean isExist = false;
try {
sftp.lstat(path);
isExist = true;
} catch (Exception e) {
if (e.getMessage().toLowerCase().equals("no such file")) {
isExist = false;
}
}
return isExist;
}
}