SFTP上传下载
程序员文章站
2022-06-01 10:40:22
...
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTPSClient;
import org.apache.log4j.Logger;
public class FTPSUtil {
private static final Logger logger = Logger.getLogger(FTPSUtil.class);
public static final String NO_FILE = "No such file";
private String username;
private String password;
private String host;
private int port;
private FTPSClient ftpClient = new FTPSClient();
private FileOutputStream fos = null;
public FTPSUtil(String username, String password, String host, int port) {
this.username = username;
this.password = password;
this.host = host;
this.port = port;
}
/**
* 连接
*/
public boolean connect() {
try {
logger.info("开始连接...");
logger.info("[username]" + username + "[host]" + host + "[port]" + port + "[password]" + password);
// 连接
this.ftpClient.connect(host, port);
int reply = this.ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
this.ftpClient.disconnect();
return false;
}
// 登录
logger.info("开始登录!");
this.ftpClient.login(username, password);
this.ftpClient.setBufferSize(1024 * 30);
this.ftpClient.setDataTimeout(600000);
this.ftpClient.setControlKeepAliveReplyTimeout(12000);
this.ftpClient.setControlKeepAliveTimeout(1200);
this.ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
this.ftpClient.execPROT("P");
this.ftpClient.enterLocalPassiveMode(); // 设置被动模式去传输
this.ftpClient.setUseEPSVwithIPv4(true);
this.ftpClient.setControlEncoding("utf8");
logger.info("登录成功!");
return true;
} catch (SocketException e) {
logger.error("连接失败!", e);
return false;
} catch (Exception e) {
logger.error("下载失败!", e);
return false;
}
}
private boolean downFileOrDirNoClose(String ftpFileName, String localDir) {
boolean flag = false;
try {
// 源文件
File file = new File(ftpFileName);
// 目标文件
File temp = new File(localDir);
if (!temp.exists()) {
temp.mkdirs();
}
ftpClient.enterLocalPassiveMode();
// 判断是否是目录
if (isDir(ftpFileName)) {
String[] names = ftpClient.listNames();
for (int i = 0; i < names.length; i++) {
logger.info(names[i] + "^^^^^^^^^^^^^^");
if (isDir(names[i])) {
downFileOrDirNoClose(ftpFileName + '/' + names[i], localDir + File.separator + names[i]);
ftpClient.changeToParentDirectory();
} else {
File localfile = new File(localDir + File.separator + names[i]);
if (!localfile.exists()) {
fos = new FileOutputStream(localfile);
ftpClient.retrieveFile(names[i], fos);
} else {
// 文件已存在,先进行删除
logger.debug("开始删除已存在文件");
file.delete();
logger.debug("已存在文件已经删除");
fos = new FileOutputStream(localfile);
ftpClient.retrieveFile(ftpFileName, fos);
}
}
}
} else {
File localfile = new File(localDir + File.separator + file.getName());
if (!localfile.exists()) {
fos = new FileOutputStream(localfile);
if (ftpClient.retrieveFile(ftpFileName, fos)) {
logger.info("下载成功");
return true;
} else {
logger.info("下载失败");
return false;
}
} else {
// 文件已存在,先进行删除
logger.debug("开始删除已存在文件");
file.delete();
logger.debug("已存在文件已经删除");
fos = new FileOutputStream(localfile);
if (ftpClient.retrieveFile(ftpFileName, fos)) {
logger.info("下载成功");
return true;
} else {
logger.info("下载失败");
return false;
}
}
}
flag = true;
} catch (SocketException e) {
logger.error("连接失败!", e);
} catch (Exception e) {
logger.error("下载失败!", e);
}
return flag;
}
/**
* 手动关闭连接
*/
public void closeFtpClient() {
try {
ftpClient.logout();
} catch (IOException e) {
logger.error("ftpClient.logout()执行失败", e);
}
close(fos);
}
/**
* 关闭连接及输出流
*
* @param fos
*/
private void close(FileOutputStream fos) {
try {
if (fos != null) {
fos.close();
}
logger.info("退出登录");
if (this.ftpClient != null) {
try {
ftpClient.disconnect();
ftpClient = null;
} catch (IOException ioe) {
logger.error("ftpClient.disconnect()执行失败", ioe);
}
}
logger.info("关闭连接");
} catch (IOException e) {
logger.error("关闭连接失败", e);
}
}
public boolean downloadFile(String ftpFileName, String localDir) {
boolean loginFlag = connect();
boolean flag = false;
if (loginFlag) {
flag = downFileOrDirNoClose(ftpFileName, localDir);
}
return flag;
}
/**
* 判断是否是目录
*
* @param fileName
* @return
*/
public boolean isDir(String fileName) {
boolean flag = false;
try {
// 切换目录,若当前是目录则返回true,否则返回false。
flag = ftpClient.changeWorkingDirectory(fileName);
} catch (Exception e) {
logger.error("判断目录失败", e);
}
return flag;
}
/**
*
* @param strRemotePath 上传目录
* @param strLocalPath 上传文件在达飞的地址
* @param remoteFileName 上传后的命名
* @return
*/
public boolean uploadFile(String strRemotePath, String strLocalPath, String remoteFileName) {
if (!this.ftpClient.isConnected()) {
connect();
}
boolean flag = false;
if (this.ftpClient.isConnected()) {
File file = new File(strLocalPath);
InputStream input = null;
try {
input = new FileInputStream(file);
if (!ftpClient.changeWorkingDirectory(strRemotePath)) {
// 如果目录不存在创建目录
String[] dirs = strRemotePath.split("/");
String tempPath = "";
for (String dir : dirs) {
if (null == dir || "".equals(dir))
continue;
tempPath += "/" + dir;
if (!ftpClient.changeWorkingDirectory(tempPath)) {
if (!ftpClient.makeDirectory(tempPath)) {
logger.error("创建远程目录失败");
} else {
ftpClient.changeWorkingDirectory(tempPath);
}
}
}
}
flag = this.ftpClient.storeFile(remoteFileName, input);
} catch (Exception e) {
logger.info("文件上传失败");
} finally {
if (input != null) {
try {
input.close();
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return flag;
}
/**
* 下载
*
* @param strUrlPath
* @param strLocalPath
* @param strFolderPath
* @return
*/
public boolean downloadFile(String strUrlPath, String strLocalPath, String strFolderPath) {
boolean result = true;
GetMethod httpGet = new GetMethod(strUrlPath);
if (!strFolderPath.equals("")) {
File Folder = new File(strFolderPath);
if (!Folder.exists()) {
System.out.println(Folder.mkdirs());
}
}
InputStream in = null;
FileOutputStream out = null;
try {
HttpClient httpClient = new HttpClient();
httpClient.executeMethod(httpGet);
in = httpGet.getResponseBodyAsStream();
out = new FileOutputStream(new File(strLocalPath));
byte[] b = new byte[1024];
int len = 0;
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
in.close();
out.close();
} catch (Exception e) {
logger.error("httpClient下载文件失败", e);
result = false;
} finally {
httpGet.releaseConnection();
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (Exception e1) {
logger.error("文件流信息关闭失败", e1);
result = false;
}
}
logger.info("####下载文件成功:" + strUrlPath);
return result;
}
public static void main(String[] args) throws FileNotFoundException {
String adder = "";
int port = 22;
String userName = "";
String passWord = "";
FTPSUtil ftp = new FTPSUtil(userName, passWord, adder, port);
ftp.uploadFile("upload/2019/04/29", "E:\\f981dbde6f944b3f974a20eed1b3b69b.zip", "test.zip");
}
}
上一篇: 这轴有毒 静音红轴键盘一月上手体验