java sftp

  1. package com.ikea.utils;   
  2.   
  3.   
  4. import java.io.File;   
  5. import java.io.FileInputStream;   
  6. import java.io.FileOutputStream;   
  7. import java.util.Properties;   
  8. import java.util.Vector;   
  9. import com.jcraft.jsch.Channel;   
  10. import com.jcraft.jsch.ChannelSftp;   
  11. import com.jcraft.jsch.JSch;   
  12. import com.jcraft.jsch.Session;   
  13. import com.jcraft.jsch.SftpException;   
  14. import com.jcraft.jsch.ChannelSftp.LsEntry;   
  15.   
  16. public class SFTPUtils {   
  17.     /**  
  18.      * 连接sftp服务器  
  19.      *   
  20.      * @param host  
  21.      *            主机  
  22.      * @param port  
  23.      *            端口  
  24.      * @param username  
  25.      *            用户名  
  26.      * @param password  
  27.      *            密码  
  28.      * @return  
  29.      */  
  30.     public ChannelSftp connect(String host, int port, String username,   
  31.             String password) {   
  32.         ChannelSftp sftp = null;   
  33.         try {   
  34.             JSch jsch = new JSch();   
  35.             jsch.getSession(username, host, port);   
  36.             Session sshSession = jsch.getSession(username, host, port);   
  37.             System.out.println("Session created.");   
  38.             sshSession.setPassword(password);   
  39.             Properties sshConfig = new Properties();   
  40.             sshConfig.put("StrictHostKeyChecking""no");   
  41.             sshSession.setConfig(sshConfig);   
  42.             sshSession.connect();   
  43.             System.out.println("Session connected.");   
  44.             System.out.println("Opening Channel.");   
  45.             Channel channel = sshSession.openChannel("sftp");   
  46.             channel.connect();   
  47.             sftp = (ChannelSftp) channel;   
  48. //          sshSession.disconnect();   
  49.             System.out.println("Connected to " + host + ".");   
  50.         } catch (Exception e) {   
  51.   
  52.         }   
  53.         return sftp;   
  54.     }   
  55.   
  56.     /**  
  57.      * 上传文件  
  58.      *   
  59.      * @param directory  
  60.      *            上传的目录  
  61.      * @param uploadFile  
  62.      *            要上传的文件  
  63.      * @param sftp  
  64.      */  
  65.     public void upload(String directory, String uploadFile, ChannelSftp sftp) {   
  66.         try {   
  67.             sftp.cd(directory);   
  68.             File file = new File(uploadFile);   
  69.             sftp.put(new FileInputStream(file), file.getName());   
  70.         } catch (Exception e) {   
  71.             e.printStackTrace();   
  72.         }   
  73.     }   
  74.   
  75.     /**  
  76.      * 下载文件  
  77.      *   
  78.      * @param directory  
  79.      *            下载目录  
  80.      * @param downloadFile  
  81.      *            下载的文件  
  82.      * @param saveFile  
  83.      *            存在本地的路径  
  84.      * @param sftp  
  85.      */  
  86.     public void download(String directory, String downloadFile,   
  87.             String saveFile, ChannelSftp sftp) {   
  88.         try {   
  89.             sftp.cd(directory);   
  90.             File file = new File(saveFile);   
  91.             sftp.get(downloadFile, new FileOutputStream(file));   
  92.         } catch (Exception e) {   
  93.             e.printStackTrace();   
  94.         }   
  95.     }   
  96.   
  97.     /**  
  98.      * 删除文件  
  99.      *   
  100.      * @param directory  
  101.      *            要删除文件所在目录  
  102.      * @param deleteFile  
  103.      *            要删除的文件  
  104.      * @param sftp  
  105.      */  
  106.     public void delete(String directory, String deleteFile, ChannelSftp sftp) {   
  107.         try {   
  108.             sftp.cd(directory);   
  109.             sftp.rm(deleteFile);   
  110.         } catch (Exception e) {   
  111.             e.printStackTrace();   
  112.         }   
  113.     }   
  114.   
  115.     /**  
  116.      * 列出目录下的文件  
  117.      *   
  118.      * @param directory  
  119.      *            要列出的目录  
  120.      * @param sftp  
  121.      * @return  
  122.      * @throws SftpException  
  123.      */  
  124.     public Vector<LsEntry> listFiles(String directory, ChannelSftp sftp)   
  125.             throws SftpException {   
  126.         return sftp.ls(directory);   
  127.     }   
  128.   
  129.     public static void main(String[] args) {   
  130.         SFTPUtils sf = new SFTPUtils();   
  131.         String host = "******";   
  132.         int port = 22;   
  133.         String username = "****";   
  134.         String password = "****";   
  135.         String directory = "/****/";   
  136.         String saveFile = "";   
  137.         String downLoadDirectory = "D:\\";   
  138.         ChannelSftp sftp = null;   
  139.         Session sshSession = null;   
  140.         try {   
  141.             JSch jsch = new JSch();   
  142.             jsch.getSession(username, host, port);   
  143.             sshSession = jsch.getSession(username, host, port);   
  144.             System.out.println("Session created.");   
  145.             sshSession.setPassword(password);   
  146.             Properties sshConfig = new Properties();   
  147.             sshConfig.put("StrictHostKeyChecking""no");   
  148.             sshSession.setConfig(sshConfig);   
  149.             sshSession.connect();   
  150.             System.out.println("Session connected.");   
  151.             System.out.println("Opening Channel.");   
  152.             Channel channel = sshSession.openChannel("sftp");   
  153.             channel.connect();   
  154.             sftp = (ChannelSftp) channel;   
  155.             System.out.println("Connected to " + host + ".");   
  156.                
  157.                
  158.                
  159. //          sf.upload(directory, uploadFile, sftp);   
  160. //          sf.download(directory, downloadFile, saveFile, sftp);   
  161.     //      sf.delete(directory, deleteFile, sftp);   
  162.            
  163. //          sftp.cd(directory);   
  164.                
  165.                
  166.             Vector<LsEntry> v = sf.listFiles(directory, sftp);   
  167.             for (LsEntry e : v) {   
  168.                 if(!e.getFilename().startsWith(".")) {   
  169.                     saveFile = downLoadDirectory + e.getFilename();   
  170.                     sf.download(directory, e.getFilename(), saveFile, sftp);   
  171.                 }   
  172.             }   
  173.             System.out.println("finished");   
  174.         } catch (Exception e) {   
  175.             e.printStackTrace();   
  176.         } finally {   
  177.             sftp.exit();   
  178.             sshSession.disconnect();   
  179.         }   
  180.     }   
  181. }  
Java 中使用 SFTP 可以借助 JSch 工具库,它是一个用于实现 SSH2 协议的 Java 库,能方便地进行 SFTP 操作。 ### 引入依赖 若使用 Maven 项目,需在 `pom.xml` 里添加 JSch 依赖: ```xml <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency> ``` ### 示例代码 以下是使用 JSch 实现 SFTP 文件上传和下载的示例代码: ```java import com.jcraft.jsch.*; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class SftpExample { public static void main(String[] args) { String host = "your_host"; int port = 22; String username = "your_username"; String password = "your_password"; String localFilePath = "local_file_path"; String remoteFilePath = "remote_file_path"; try { // 创建 JSch 实例 JSch jsch = new JSch(); // 获取会话 Session session = jsch.getSession(username, host, port); // 设置密码 session.setPassword(password); // 避免 SSH 密钥检查 java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); // 连接会话 session.connect(); // 打开 SFTP 通道 Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; // 上传文件 uploadFile(sftpChannel, localFilePath, remoteFilePath); // 下载文件 downloadFile(sftpChannel, remoteFilePath, localFilePath); // 关闭通道和会话 sftpChannel.exit(); session.disconnect(); } catch (JSchException | SftpException | IOException e) { e.printStackTrace(); } } public static void uploadFile(ChannelSftp sftpChannel, String localFilePath, String remoteFilePath) throws SftpException, IOException { File localFile = new File(localFilePath); FileInputStream fis = new FileInputStream(localFile); sftpChannel.put(fis, remoteFilePath); fis.close(); System.out.println("文件上传成功"); } public static void downloadFile(ChannelSftp sftpChannel, String remoteFilePath, String localFilePath) throws SftpException, IOException { File localFile = new File(localFilePath); FileOutputStream fos = new FileOutputStream(localFile); sftpChannel.get(remoteFilePath, fos); fos.close(); System.out.println("文件下载成功"); } } ``` ### 代码解释 1. **引入依赖**:借助 Maven 引入 JSch 库。 2. **创建会话**:利用 `JSch` 创建会话并连接到 SFTP 服务器。 3. **打开通道**:打开 SFTP 通道并连接。 4. **文件上传**:使用 `put` 方法把本地文件上传到远程服务器。 5. **文件下载**:使用 `get` 方法从远程服务器下载文件到本地。 6. **关闭连接**:操作完成后,关闭通道和会话。 ### 注意事项 - 要将示例代码中的 `your_host`、`your_username`、`your_password`、`local_file_path` 和 `remote_file_path` 替换成实际的值。 - 运行代码前需确保 SFTP 服务器正常运行,且具备相应的访问权限。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值