sftp上傳本地文件,實現sftp鏈接,并下載服務器上文件

 2023-12-10 阅读 32 评论 0

摘要:首先,需要在pom文件中引入鏈接sftp的依賴,我這里用的是jsch,如下: <dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.54</version></dependency> 其次

首先,需要在pom文件中引入鏈接sftp的依賴,我這里用的是jsch,如下:

<dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.54</version></dependency>

其次,建立sftp鏈接工具類:

package com.apache.https.sinosoft.common;import com.jcraft.jsch.*;import java.io.*;
import java.util.*;public class FTPUtils {/*** sftp工具類**/private ChannelSftp sftp = null;private Session sshSession = null;/*** 通過SFTP連接服務器*/public void connect(String ip,String port,String userName,String password){try{System.out.println("sft鏈接開始---》connect---begin");int sftpPort = 22;//端口號if(null != port && !"".equals(port)){sftpPort = Integer.valueOf(port);}JSch jsch = new JSch();jsch.getSession(userName, ip, sftpPort);sshSession = jsch.getSession(userName, ip, sftpPort);System.out.println("ip="+ip+"--->port"+port);sshSession.setPassword(password);Properties sshConfig = new Properties();sshConfig.put("StrictHostKeyChecking", "no");sshSession.setConfig(sshConfig);// 登錄sshSession.connect();System.out.println("sftp鏈接成功------>success");Channel channel = sshSession.openChannel("sftp");channel.connect();sftp = (ChannelSftp) channel;System.out.println("sft鏈接結束---》connect---end");}catch (Exception e){e.printStackTrace();}}/*** 關閉連接*/public void disconnect() {System.out.println("sft關閉鏈接開始---》disconnect---begin");if (this.sftp != null) {if (this.sftp.isConnected()) {this.sftp.disconnect();}}if (this.sshSession != null) {if (this.sshSession.isConnected()) {this.sshSession.disconnect();}}System.out.println("sft關閉鏈接結束---》disconnect---end");}/*** 批量下載文件** @param remotePath:遠程下載目錄(以路徑符號結束,可以為相對路徑eg:/assess/sftp/jiesuan_2/2014/)* @param localPath:本地保存目錄(以路徑符號結束,D:\Duansha\sftp\)* @param fileFormat:下載文件格式(以特定字符開頭,為空不做檢驗)* @param fileEndFormat:下載文件格式(文件格式)* @param del:下載后是否刪除sftp文件* @return*/public List<String> batchDownLoadFile(String remotePath, String localPath,String fileFormat, String fileEndFormat, boolean del) {List<String> filenames = new ArrayList<String>();try {// connect();Vector v = listFiles(remotePath);// sftp.cd(remotePath);if (v.size() > 0) {System.out.println("本次處理文件個數不為零,開始下載...fileSize=" + v.size());Iterator it = v.iterator();while (it.hasNext()) {ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();String filename = entry.getFilename();SftpATTRS attrs = entry.getAttrs();if (!attrs.isDir()) {boolean flag = false;String localFileName = localPath + filename;fileFormat = fileFormat == null ? "" : fileFormat.trim();fileEndFormat = fileEndFormat == null ? "": fileEndFormat.trim();// 三種情況if (fileFormat.length() > 0 && fileEndFormat.length() > 0) {if (filename.startsWith(fileFormat) && filename.endsWith(fileEndFormat)) {flag = downloadFile(remotePath, filename, localPath, filename);if (flag) {filenames.add(localFileName);if (flag && del) {deleteSFTP(remotePath, filename);}}}} else if (fileFormat.length() > 0 && "".equals(fileEndFormat)) {if (filename.startsWith(fileFormat)) {flag = downloadFile(remotePath, filename, localPath, filename);if (flag) {filenames.add(localFileName);if (flag && del) {deleteSFTP(remotePath, filename);}}}} else if (fileEndFormat.length() > 0 && "".equals(fileFormat)) {if (filename.endsWith(fileEndFormat)) {flag = downloadFile(remotePath, filename, localPath, filename);if (flag) {filenames.add(localFileName);if (flag && del) {deleteSFTP(remotePath, filename);}}}} else {flag = downloadFile(remotePath, filename, localPath, filename);if (flag) {filenames.add(localFileName);if (flag && del) {deleteSFTP(remotePath, filename);}}}}}}} catch (SftpException e) {e.printStackTrace();} finally {// this.disconnect();}return filenames;}/*** 下載單個文件** @param ftpPath:遠程下載目錄(以路徑符號結束)* @param remoteFileName:下載文件名* @param localPath:本地保存目錄(以路徑符號結束)* @param localFileName:保存文件名* @return*/public boolean downloadFile(String ftpPath, String remoteFileName, String localPath, String localFileName) {FileOutputStream fieloutput = null;System.out.println("sftp下載文件開始----->downLoad---begin");try {System.out.println("本地文件路徑名稱"+localPath + localFileName);File file1 = new File(localPath);if(!file1.exists()){file1.mkdirs();}File file = new File(localPath + localFileName);fieloutput = new FileOutputStream(file);System.out.println("服務器文件路徑名稱"+ftpPath + remoteFileName);sftp.get(ftpPath + remoteFileName, fieloutput);System.out.println("sftp下載文件結束----->downLoad---end");return true;} catch (FileNotFoundException e) {e.printStackTrace();} catch (SftpException e) {e.printStackTrace();} finally {if (null != fieloutput) {try {fieloutput.close();} catch (IOException e) {e.printStackTrace();}}}return false;}/*** 上傳單個文件** @param remotePath:遠程保存目錄* @param remoteFileName:保存文件名* @param localPath:本地上傳目錄(以路徑符號結束)* @param localFileName:上傳的文件名* @return*/public boolean uploadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {FileInputStream in = null;try {createDir(remotePath);File file = new File(localPath + localFileName);in = new FileInputStream(file);sftp.put(in, remoteFileName);return true;} catch (FileNotFoundException e) {e.printStackTrace();} catch (SftpException e) {e.printStackTrace();} finally {if (in != null) {try {in.close();} catch (IOException e) {e.printStackTrace();}}}return false;}/*** 批量上傳文件** @param remotePath:遠程保存目錄* @param localPath:本地上傳目錄(以路徑符號結束)* @param del:上傳后是否刪除本地文件* @return*/public boolean bacthUploadFile(String remotePath, String localPath, boolean del) {try {File file = new File(localPath);File[] files = file.listFiles();for (int i = 0; i < files.length; i++) {if (files[i].isFile()&& files[i].getName().indexOf("bak") == -1) {if (this.uploadFile(remotePath, files[i].getName(),localPath, files[i].getName())	&& del) {deleteFile(localPath + files[i].getName());}}}return true;} catch (Exception e) {e.printStackTrace();} finally {this.disconnect();}return false;}/*** 刪除本地文件** @param filePath* @return*/public boolean deleteFile(String filePath) {File file = new File(filePath);if (!file.exists()) {return false;}if (!file.isFile()) {return false;}boolean rs = file.delete();return rs;}/*** 創建目錄** @param createpath* @return*/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);return true;} catch (SftpException e) {e.printStackTrace();}return false;}/*** 判斷目錄是否存在** @param directory* @return*/public boolean isDirExist(String directory) {boolean isDirExistFlag = false;try {SftpATTRS sftpATTRS = sftp.lstat(directory);isDirExistFlag = true;return sftpATTRS.isDir();} catch (Exception e) {if (e.getMessage().toLowerCase().equals("no such file")) {isDirExistFlag = false;}}return isDirExistFlag;}/*** 刪除stfp文件** @param directory:要刪除文件所在目錄* @param deleteFile:要刪除的文件*/public void deleteSFTP(String directory, String deleteFile) {try {// sftp.cd(directory);sftp.rm(directory + deleteFile);} catch (Exception e) {e.printStackTrace();}}/*** 如果目錄不存在就創建目錄** @param path*/public void mkdirs(String path) {File f = new File(path);String fs = f.getParent();f = new File(fs);if (!f.exists()) {f.mkdirs();}}/*** 列出目錄下的文件** @param directory:要列出的目錄* @return* @throws SftpException*/public Vector listFiles(String directory) throws SftpException {return sftp.ls(directory);}/*** 測試*/public static void main(String[] args) {FTPUtils sftp = null;// 本地存放地址String localPath = "D:/tomcat5/webapps/ASSESS/DocumentsDir/DocumentTempDir/txtData/";// Sftp下載路徑String sftpPath = "/home/assess/sftp/jiesuan_2/2014/";List<String> filePathList = new ArrayList<String>();try {
//			sftp = new FTPUtils("10.163.201.115", "tdcp", "tdcp");sftp.connect("10.163.201.115", "21", "tdcp","tdcp");// 下載sftp.batchDownLoadFile(sftpPath, localPath, "ASSESS", ".txt", true);} catch (Exception e) {e.printStackTrace();} finally {sftp.disconnect();}}
}

這里我用的是批量文件下載,代碼如下:

String date = request.getParameter("date");String ftpIP = SysConfig.getPropertity("ZBFFTPIP"); // ipString ftpPort = SysConfig.getPropertity("ZBFFTPPORT"); // port端口String ftpUserName = SysConfig.getPropertity("ZBFFTPUSERNAME"); // 用戶名String ftpPassWord = SysConfig.getPropertity("ZBFFTPPASSWORD"); // 密碼String ftpPath = SysConfig.getPropertity("ZBFFTPPATH");// ftp路徑String localFilePath = SysConfig.getPropertity("RECONCILIATIONFILEPATH"); // 本地路徑// 從sftp下載路徑String path = ftpPath;FTPUtils sftp = new FTPUtils();try {// 鏈接sftp進行對賬文件下載sftp.connect(ftpIP,ftpPort,ftpUserName,ftpPassWord);List<String> strings = sftp.batchDownLoadFile(path+date+"/", localFilePath+date+"/", "", ".txt", false);} catch (Exception e) {e.printStackTrace();} finally {sftp.disconnect();response.flushBuffer();}

工具類中也有其他的方法可以調用,大家可以試一下。

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://808629.com/196175.html

上一篇:linux操作sftp

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 86后生记录生活 Inc. 保留所有权利。

底部版权信息