SFTP的使用:
1.項目中需要引入jar包,下載地址:https://sourceforge.net/projects/jsch/files/jsch.jar/
2.需要下載SFTP服務器,下載地址:http://www.freesshd.com/?ctt=download
服務器的配置參考:http://www.cnblogs.com/zxx-813/p/7353806.html、http://jingyan.baidu.com/article/f7ff0bfc1ebd322e27bb1344.html
3.java代碼(基於SFTP上傳、下載文件(單個以及批量)):
ChannelSftp使用api:http://epaul.github.io/jsch-documentation/javadoc/index.html?com/jcraft/jsch/ChannelSftp.html
package test.sftp; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.Vector; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.ChannelSftp.LsEntry; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpATTRS; import com.jcraft.jsch.SftpException; public class Test2 { private static ChannelSftp sftp = null; private static String host = "127.0.0.1"; private static int port = 22; private static String username = "root"; private static String password = "root"; private static Session sshSession = null; /** * main方法 * @param args */ public static void main(String[] args) { ChannelSftp channelSftp = connect(host, port, username, password); System.out.println(channelSftp); sftp = channelSftp; /** * 上傳單個文件 * @param remotePath:遠程保存目錄 * @param remoteFileName:保存文件名 * @param localPath:本地上傳目錄(以路徑符號結束) * @param localFileName:上傳的文件名 * @return */ /*String remotePath = "/test1/"; //遠程保存目錄 String remoteFileName = "test.rar"; //保存文件名 String localPath = "C:\\Users\\lyc\\Desktop\\"; //本地上傳目錄(以路徑符號結束) String localFileName = "msftpsrvr.rar"; //reservation3.sql //上傳的文件名 uploadFile(remotePath,remoteFileName,localPath,localFileName);*/ /** * 下載單個文件 * @param directory:下載目錄 * @param downloadFile:下載的文件 * @param saveFile:存在本地的路徑 * @param sftp */ /*String directory = "/test/"; //下載目錄 String downloadFile = "test.sql"; //下載的文件 String saveFile = "D:\\"; //存在本地的路徑 download(directory,downloadFile,saveFile,sftp);*/ /** * 批量上傳文件 * @param remotePath:遠程保存目錄 * @param localPath:本地上傳目錄(以路徑符號結束) * @param del:上傳后是否刪除本地文件 * @return */ /*String remotePath = "/test/"; String localPath = "C:/Users/lyc/Desktop/aa/"; boolean del = false; bacthUploadFile(remotePath,localPath,del);*/ /** * 批量下載文件 * @param remotPath:遠程下載目錄(以路徑符號結束,可以為相對路徑eg:/assess/sftp/jiesuan_2/2014/) * @param localPath:本地保存目錄(以路徑符號結束,D:\Duansha\sftp\) * @param fileFormat:下載文件格式(以特定字符開頭,為空不做檢驗) * @param fileEndFormat:下載文件格式(文件格式) * @param del:下載后是否刪除sftp文件 * @return */ String remotePath = "/test/"; String localPath = "C:/Users/lyc/Desktop/aa/"; String fileFormat = ""; //下載特定字符開頭的文件 String fileEndFormat = "x"; //下載某一種格式的文件(下載特定字符結尾的文件) boolean del = false; batchDownLoadFile(remotePath,localPath,fileFormat,fileEndFormat,del); } /** * 鏈接sftp服務器 * @param host 服務器地址 * @param port 服務器端口 * @param username 登錄用戶名 * @param password 登錄密碼 * @return */ public static ChannelSftp connect(String host,int port,String username,String password){ ChannelSftp sftp = null; JSch jsch = new JSch(); try { sshSession = jsch.getSession(username, host, port); System.out.println("創建session!"); sshSession.setPassword(password); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); System.out.println("session鏈接"); Channel channel = sshSession.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp)channel; System.out.println("成功鏈接到"+host+"."); } catch (JSchException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sftp; } /** * 上傳單個文件 * @param remotePath:遠程保存目錄 * @param remoteFileName:保存文件名 * @param localPath:本地上傳目錄(以路徑符號結束) * @param localFileName:上傳的文件名 * @return */ public static 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 createpath 遠程保存目錄 * @return */ public static boolean createDir(String createpath) { try { if (isDirExist(createpath)){ //文件存在 sftp.cd(createpath); //cd()更改當前遠程目錄 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()); //mkdir()創建一個新的遠程目錄 // 進入並設置為當前目錄 sftp.cd(filePath.toString()); } } sftp.cd(createpath); return true; } catch (SftpException e){ e.printStackTrace(); } return false; } /** * 判斷目錄是否存在 * @param directory * @return */ public static boolean isDirExist(String directory){ boolean isDirExistFlag = false; try{ SftpATTRS sftpATTRS = sftp.lstat(directory); //lstat()檢索文件或目錄的文件屬性 isDirExistFlag = true; System.out.println(sftpATTRS.isDir()); return sftpATTRS.isDir(); //isDir()檢查此文件是否為目錄 }catch (Exception e){ if (e.getMessage().toLowerCase().equals("no such file")){ isDirExistFlag = false; } } return isDirExistFlag; } /** * 下載單個文件 * @param directory 下載目錄 * @param downloadFile 下載的文件 * @param saveFile 存在本地的路徑 * @param sftp */ public static void download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) { try { sftp.cd(directory); //下載目錄 sftp.get(downloadFile,saveFile); //下載的文件 存在本地的路徑 }catch (Exception e){ e.printStackTrace(); } } /** * 批量上傳文件 * @param remotePath:遠程保存目錄 * @param localPath:本地上傳目錄(以路徑符號結束) * @param del:上傳后是否刪除本地文件 * @return */ public static boolean bacthUploadFile(String remotePath, String localPath, boolean del) { try { /*connect();*/ 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 (uploadFile(remotePath, files[i].getName(), localPath, files[i].getName()) && del){ //上傳文件 deleteFile(localPath + files[i].getName()); //上傳后刪除本地文件 } } } /*if (log.isInfoEnabled()) { log.info("upload file is success:remotePath=" + remotePath + "and localPath=" + localPath + ",file size is " + files.length); }*/ return true; }catch (Exception e){ e.printStackTrace(); }finally{ disconnect(); } return false; } /** * 刪除本地文件 * @param filePath * @return */ public static boolean deleteFile(String filePath){ File file = new File(filePath); if (!file.exists()){ return false; } if (!file.isFile()){ return false; } boolean rs = file.delete(); /*if (rs && log.isInfoEnabled()) { log.info("delete file success from local."); }*/ return rs; } /** * 關閉連接 */ public static void disconnect(){ if (sftp != null){ if (sftp.isConnected()){ sftp.disconnect(); /*if (log.isInfoEnabled()) { log.info("sftp is closed already"); }*/ } } if (sshSession != null){ if (sshSession.isConnected()){ sshSession.disconnect(); /*if (log.isInfoEnabled()) { log.info("sshSession is closed already"); }*/ } } } /** * 批量下載文件 * @param remotPath:遠程下載目錄(以路徑符號結束,可以為相對路徑eg:/assess/sftp/jiesuan_2/2014/) * @param localPath:本地保存目錄(以路徑符號結束,D:\Duansha\sftp\) * @param fileFormat:下載文件格式(以特定字符開頭,為空不做檢驗) * @param fileEndFormat:下載文件格式(文件格式) * @param del:下載后是否刪除sftp文件 * @return */ @SuppressWarnings("rawtypes") public static 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); Vector v = sftp.ls(remotePath); //lstat(String path):列出遠程目錄的內容 // sftp.cd(remotePath); if (v.size() > 0) { System.out.println("本次處理文件個數不為零,開始下載...fileSize=" + v.size()); Iterator it = v.iterator(); while (it.hasNext()) { LsEntry entry = (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); } } } } } } /*if (log.isInfoEnabled()) { log.info("download file is success:remotePath=" + remotePath + "and localPath=" + localPath + ",file size is" + v.size()); }*/ } catch (SftpException e) { e.printStackTrace(); } finally { // this.disconnect(); } return filenames; } /** * 下載單個文件 * @param remotPath:遠程下載目錄(以路徑符號結束) * @param remoteFileName:下載文件名 * @param localPath:本地保存目錄(以路徑符號結束) * @param localFileName:保存文件名 * @return */ public static boolean downloadFile(String remotePath, String remoteFileName,String localPath, String localFileName) { FileOutputStream fieloutput = null; try { // sftp.cd(remotePath); File file = new File(localPath + localFileName); // mkdirs(localPath + localFileName); fieloutput = new FileOutputStream(file); sftp.get(remotePath + remoteFileName, fieloutput); /*if (log.isInfoEnabled()) { log.info("===DownloadFile:" + remoteFileName + " success from sftp."); }*/ 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; } /** * 刪除stfp文件 * @param directory:要刪除文件所在目錄 * @param deleteFile:要刪除的文件 * @param sftp */ public static void deleteSFTP(String directory, String deleteFile) { try { // sftp.cd(directory); sftp.rm(directory + deleteFile); /*if (log.isInfoEnabled()) { log.info("delete file success from sftp."); }*/ } catch (Exception e) { e.printStackTrace(); } } /** * 列出目錄下的文件 * * @param directory:要列出的目錄 * @param sftp * @return * @throws SftpException */ /*@SuppressWarnings("rawtypes") public static Vector listFiles(String directory) throws SftpException { return sftp.ls(directory); }*/ }
