通過Jsch實現SFTP檔案上傳下載拷貝刪除操作
阿新 • • 發佈:2019-02-08
1.在pom.xml檔案中引入JAR包:
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
2.編寫工具類SftpUtils.java,該工具類可直接拷貝使用
import com.jcraft.jsch.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.*; public class SftpUtils { private Logger logger = LoggerFactory.getLogger(SftpUtils.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); System.out.println("Session created."); sshSession.setPassword(password); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); System.out.println("Session connected."); System.out.println("Opening Channel."); Channel channel = sshSession.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; System.out.println("Connected to " + host + "."); } catch (Exception e) { e.printStackTrace(); sftp = null; } return sftp; } public ChannelSftp connectSftp(Session sshSession) { ChannelSftp sftp = null; try { System.out.println("Session connected."); System.out.println("Opening Channel."); Channel channel = sshSession.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; } catch (Exception e) { e.printStackTrace(); sftp = null; } return sftp; } public void exec(Session sshSession,String command) { ChannelExec channelExec = null; try { System.out.println("Session connected."); System.out.println("Opening Channel."); Channel channel = sshSession.openChannel("exec"); channelExec = (ChannelExec) channel; channelExec.setCommand(command); channelExec.connect(); } catch (Exception e) { e.printStackTrace(); channelExec = null; }finally { channelExec.disconnect(); } } public Session getSession(String host, int port, String username, String password) { Session sshSession = null; try { JSch jsch = new JSch(); jsch.getSession(username, host, port); sshSession = jsch.getSession(username, host, port); System.out.println("Session created."); sshSession.setPassword(password); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); System.out.println("Session connected."); System.out.println("Opening Channel."); } catch (Exception e) { e.printStackTrace(); } return sshSession; } /** * 上傳檔案 * * @param directory * 上傳的目錄 * @param uploadFile * 要上傳的檔案 * @param sftp */ public String upload(String directory, String uploadFile, ChannelSftp sftp) { try { if(!directory.equals("")){ sftp.cd(directory); } File file = new File(uploadFile); sftp.put(new FileInputStream(file), file.getName()); System.out.println("上傳完成"); sftp.disconnect(); sftp.getSession().disconnect(); return "傳輸成功"; } catch (Exception e) { e.printStackTrace(); sftp.disconnect(); try { sftp.getSession().disconnect(); } catch (JSchException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return "傳輸失敗,請檢查配置!"; } } /** * 下載檔案 * * @param directory * 下載目錄 * @param downloadFile * 下載的檔案 * @param saveFile * 存在本地的路徑 * @param sftp */ public void download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) { try { sftp.cd(directory); File file = new File(saveFile); sftp.get(downloadFile, new FileOutputStream(file)); sftp.disconnect(); sftp.getSession().disconnect(); System.out.println("download ok,session closed"); } catch (Exception e) { sftp.disconnect(); try { sftp.getSession().disconnect(); } catch (JSchException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); } } public List<String> read(String directory, String readFile, ChannelSftp sftp,String charSetName) { List<String> stringlist = new ArrayList<>(); InputStream inputStream = null; try { sftp.cd(directory); inputStream = sftp.get(readFile); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,charSetName)); String line = null; line = br.readLine(); while (line != null) { stringlist.add(line); line = br.readLine(); // 一次讀入一行資料 } br.close(); } catch (SftpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return stringlist; } /** * 刪除檔案 * * @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) { e.printStackTrace(); } } /** * 列出目錄下的檔案 * * @param directory * 要列出的目錄 * @param sftp * @return * @throws SftpException */ public Vector listFiles(String directory, ChannelSftp sftp) throws SftpException { return sftp.ls(directory); } /** * 將輸入流的資料上傳到sftp作為檔案 * * @param directory * 上傳到該目錄 * @param sftpFileName * sftp端檔名 * @param input * 輸入流 * @throws SftpException * @throws Exception */ public void upload(String directory, String sftpFileName, InputStream input,ChannelSftp sftp) throws SftpException, JSchException { try { sftp.cd(directory); } catch (SftpException e) { logger.warn("directory is not exist"); sftp.mkdir(directory); sftp.cd(directory); } sftp.put(input, sftpFileName); if(sftp.isConnected()) { sftp.disconnect(); } if (sftp.getSession().isConnected()) { sftp.getSession().disconnect(); } logger.info("file:{"+sftpFileName+"} is upload successful"); }
3.呼叫JSCH工具類方法獲取遠端伺服器中.txt字尾的檔案內容:
public List<Student> readFile(String host,int port,String userName,String passWord,String srcDirectory,String bakDirectory,String filterKey){ List<Student> students = new ArrayList<>(); SftpUtils sf = new SftpUtils(); Session session = sf.getSession(host, port, userName, passWord); ChannelSftp sftp = sf.connectSftp(session); //連線 String date = "20180601"; String bakFolder = bakDirectory + "/" + date; //備份目錄 SftpATTRS isExist = null; try { isExist = sftp.stat(bakFolder);//判斷備份目錄是否存在,不存在則建立 if(isExist==null){ sftp.mkdir(bakFolder); } } catch (SftpException e) { } try { sftp.cd(srcDirectory);//進入源目錄 Vector<ChannelSftp.LsEntry> vector = sftp.ls(filterFileKey);//獲取該目錄下匹配的檔案 logger.info("ls " + filterKey); logger.info("file total num " + vector.size()); for (ChannelSftp.LsEntry lsEntry:vector) { if(lsEntry != null){ String filleName = lsEntry.getFilename(); logger.info("read the file "+filleName ); try { List<String> list = sf.read(srcDirectory, filleName, sftp,"GBK"); for (int i = 0; i < list.size(); i++) { String content = list.get(i); if(content!=null) { Student student = new Student(); String[] args = content.split("\\|"); student.setId(args[0]); student.setName(args[1]); students.add(student); } } //移動檔案到備份目錄 String command = "mv "+(srcDirectory + "/" + filleName) + " " + bakDirectory + "/" + date + "/"; logger.info(command); sf.exec(session,command); }catch (Exception ex){ ex.printStackTrace(); } } } } catch (SftpException e) { e.printStackTrace(); }finally { sftp.disconnect(); try { sftp.getSession().disconnect(); } catch (JSchException e) { e.printStackTrace(); } } return students; }