1.創建FileUtils,
package com.mischen.pay.common.utils;
import java.io.File;
/**
* 文件工具類
* @author Peter
*
*/
public class FileUtils {
/**
* 傳入文件夾路徑,該方法能夠實現創建整個路徑
* @param path 文件夾路徑,不包含文件名稱及後綴名
*/
public static void isDir(String path){
String[] paths = path.split("/");
String filePath = "";
for(int i = 0 ; i < paths.length ; i++){
if(i == 0){
filePath = paths[0];
}else{
filePath += "/" + paths[i];
}
creatDir(filePath);
}
}
/**
* 該方法用來判斷文件夾是否存在,如果不存在則創建,存在則什麼都不做
* @param filePath
*/
public static void creatDir(String filePath){
File file = new File(filePath);
if(!file.exists()){
file.mkdir();
}
}
}
2.創建Sftp類
package com.mischen.pay.common.utils.sftp;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import java.util.Vector;
import org.apache.log4j.Logger;
import com.mischen.pay.common.utils.FileUtils;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
/**
* ClassName: Sftp 連接類包括上傳下載<br/>
* Function: <br/>
* @author:mischen
* @date:2020/4/5 17:19
*/
public class Sftp {
private static final Logger LOG = Logger.getLogger(Sftp.class);
/**
* 連接sftp服務器
*
* @param host
* 主機
* @param port
* 端口
* @param username
* 用戶名
* @param password
* 密碼
* @return
*/
public ChannelSftp connect(String host, int port, String username, String password) {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
// jsch.getSession(username, host, port);
Session sshSession = jsch.getSession(username, host, port);
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;
} catch (Exception e) {
LOG.error("sftp connect exception:", e);
}
return sftp;
}
/**
* 上傳文件
*
* @param directory
* 上傳的目錄
* @param uploadFile
* 要上傳的文件
* @param channel
*/
public static void upload(String directory, String uploadFile, ChannelSftp channel) {
try {
creatDir(directory, channel);
channel.cd(directory);
File file = new File(uploadFile);
channel.put(new FileInputStream(file), file.getName());
sftpClose(channel);
} catch (Exception e) {
LOG.error("sftp upload exception:", e);
}finally {
if (channel != null) {
sftpClose(channel);
}
}
}
/**
* 下載文件
*
* @param directory
* 下載目錄
* @param downloadFilePath
* 下載的文件
* @param saveFile
* 存在本地的路徑
* @param channel
*/
public static void download(String directory, String downloadFilePath, String saveFile, ChannelSftp channel) {
try {
channel.cd(directory);
File file = new File(saveFile);
channel.get(downloadFilePath, new FileOutputStream(file));
} catch (Exception e) {
LOG.error("sftp download exception:", e);
}finally {
if (channel != null) {
sftpClose(channel);
}
}
}
/**
* 下載文件
*
* @param directory
* 下載目錄
* @param downloadFile
* 下載的文件
* @param saveFile
* 存在本地的路徑
* @param channelSftp
*/
public static String downloadGetString(String directory, String downloadFile, String saveFile, ChannelSftp channelSftp) {
try {
channelSftp.cd(directory);
File file = new File(saveFile);
channelSftp.get(downloadFile, new FileOutputStream(file));
return readFileByLines(file.getPath());
} catch (Exception e) {
LOG.error("sftp downloadGetString excetpin:", e);
}
return null;
}
/**
* 以行爲單位讀取文件,常用於讀面向行的格式化文件
*/
public static String readFileByLines(String fileName) {
StringBuffer sb = new StringBuffer();
File file = new File(fileName);
BufferedReader reader = null;
try {
// 以行爲單位讀取文件內容,一次讀一整行
reader = new BufferedReader(new FileReader(file));
String tempString = null;
// 一次讀入一行,直到讀入null爲文件結束
while ((tempString = reader.readLine()) != null) {
// 顯示行號
sb.append(tempString);
}
reader.close();
} catch (IOException e) {
LOG.error(e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
LOG.error("BufferedReader close exception:", e);
}
}
}
return sb.toString();
}
/**
* 刪除文件
*
* @param directory
* 要刪除文件所在目錄
* @param deleteFile
* 要刪除的文件
* @param sftp
*/
public void delete(String directory, String deleteFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
sftp.rm(deleteFile);
} catch (Exception e) {
LOG.error(e);
}
}
/**
* 列出目錄下的文件
*
* @param directory
* 要列出的目錄
* @param sftp
* @return
* @throws SftpException
*/
public Vector listFiles(String directory, ChannelSftp sftp) throws SftpException {
return sftp.ls(directory);
}
/**
* 根據傳入的目錄創建文件夾
*
* @param directory
* @param sftp
* @throws SftpException
*/
public static void creatDir(String directory, ChannelSftp sftp) throws SftpException {
String[] dirArr = directory.split("/");
StringBuffer tempStr = new StringBuffer("");
for (int i = 1; i < dirArr.length; i++) {
tempStr.append("/" + dirArr[i]);
try {
sftp.cd(tempStr.toString());
} catch (SftpException e) {
sftp.mkdir(tempStr.toString());
}
}
}
/**
* sftpClose:關閉Sftp <br/>
*
* @param channel
*/
public static void sftpClose(ChannelSftp channel) {
try {
channel.getSession().disconnect();
} catch (JSchException e) {
LOG.error("sftp disconnect exception:", e);
}
}
/***
* 連接SFTP服務器,根據文件路徑讀取文件文本內容.<br/>
*
* @param dataFilePath
* SFTP保存的文件全路徑
* @return 文件內容.
*/
public static String getFileContentFormSFTP(final ChannelSftp channelSftp, final String dataFilePath) {
String property = System.getProperty("user.dir") + File.separator + "temp/";
FileUtils.isDir(property);
String directory = dataFilePath.substring(0, dataFilePath.lastIndexOf("/")); // 文件路徑
String downloadFile = dataFilePath.substring(dataFilePath.lastIndexOf("/") + 1); // 文件名稱
String saveFile = property + "/" + downloadFile; // 保存文件路徑
LOG.info("==>從SFTP獲取文件內容,源文件路徑[" + dataFilePath + "], 保存本地的臨時文件路徑[" + saveFile + "]");
return downloadGetString(directory, downloadFile, saveFile, channelSftp);
}
/**
* 從SFTP服務器上下載文件
*
* @return
*/
public static File downFileFromSFTP(ChannelSftp channelSftp, final String filePath) {
// 創建臨時目錄,用來存放下載的文件
StringBuffer tempFilePath = new StringBuffer(System.getProperty("user.dir")).append(File.separator).append("temp");
isDir(tempFilePath.toString());
String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
String tempPath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
// 創建臨時返回文件
String saveFile = tempFilePath + "/" + fileName;
File returnFile = new File(saveFile);
try {
download(tempPath, fileName, saveFile, channelSftp);
} catch (Exception e) {
LOG.error("==>對賬文件下載失敗:", e);
} finally {
if (channelSftp != null) {
sftpClose(channelSftp);
}
}
return returnFile;
}
/**
* 傳入文件夾路徑,該方法能夠實現創建整個路徑
*
* @param path
* 文件夾路徑,不包含文件名稱及後綴名
*/
public static void isDir(String path) {
String[] paths = path.split("/");
String filePath = "";
for (int i = 0; i < paths.length; i++) {
if (i == 0) {
filePath = paths[0];
} else {
filePath += "/" + paths[i];
}
creatDir(filePath);
}
}
/**
* 該方法用來判斷文件夾是否存在,如果不存在則創建,存在則什麼都不做
*
* @param filePath
*/
public static void creatDir(String filePath) {
File file = new File(filePath);
if (!file.exists()) {
file.mkdir();
}
}
// 測試例子
public static void main(String[] args) {
Sftp sf = new Sftp();
String host = "192.168.28.49";
int port = 3210;
String username = "mischen";
String password = "123.com";
String directory = "/home/mischen/";
String downloadFile = "Result.txt";
String saveFile = "F:\\123.txt";
String uploadFile = "E:\\1.txt";
// String deleteFile = "delete.txt";
ChannelSftp sftp = sf.connect(host, port, username, password);
sf.upload(directory, uploadFile, sftp);
// sf.download(directory, downloadFile, saveFile, sftp);
// sf.delete(directory, deleteFile, sftp);
try {
// sf.creatDir(directory, sftp);
// sftp.cd(directory);
// System.out.println("finished");
// sf.sftpClose(sftp);
} catch (Exception e) {
LOG.error(e);
} finally {
if (sf != null){
sf.sftpClose(sftp);
}
}
}
}