分享

详解sftp实现对远程服务器的文件操作

 WindySky 2017-09-20

该所有操作依赖的jsch的jar包     jsch-0.1.50.jar

 以下为本人整理的相关SFTP对服务器文件的相关操作,具体的操作方方法依赖于ChannelSftp对象,刻字机单独进行封装,本处就不贴出完整的工具类了


1:获得 ChannelSftp对象


  1. public class SftpUtil {  
  2.     private static final Logger LOG = LogManager.getLogger(SftpUtil.class);  
  3.     private static SftpUtil sftpUtil;  
  4.     private static ChannelSftp sftp;  
  5.     private String host;  
  6.     private int port;  
  7.     private String userName;  
  8.     private String password;  
  9.   
  10.     private SftpUtil(String host, int port, String userName, String password) {  
  11.         this.host = host;  
  12.         this.port = port;  
  13.         this.userName = userName;  
  14.         this.password = password;  
  15.     }  
  16.   
  17.     /**  
  18.      * 获得Smb连接对象  
  19.      *   
  20.      * @Title: getInstance  
  21.      * @param url  
  22.      * @return SmbUtil  
  23.      * @author wangqinghua  
  24.      * @date 2015-9-22 下午7:39:41  
  25.      */  
  26.     public static synchronized SftpUtil getInstance(String host, int port,  
  27.             String userName, String password) {  
  28.         if (sftpUtil == null) {  
  29.             sftpUtil = new SftpUtil(host, port, userName, password);  
  30.         }  
  31.         return sftpUtil;  
  32.     }  
  33.   
  34.     /**  
  35.      * 连接初始化  
  36.      *   
  37.      * @Title: init void  
  38.      * @author wangqinghua  
  39.      * @date 2015-9-22 下午7:40:50  
  40.      */  
  41.     public ChannelSftp getSftp() {  
  42.         JSch jsch = new JSch();  
  43.         Channel channel = null;  
  44.         try {  
  45.             Session sshSession = jsch.getSession(this.userName, this.host, this.port);  
  46.             sshSession.setPassword(password);  
  47.             Properties sshConfig = new Properties();  
  48.             sshConfig.put("StrictHostKeyChecking", "no");  
  49.             sshSession.setConfig(sshConfig);  
  50.             sshSession.connect(20000);  
  51.             channel = sshSession.openChannel("sftp");  
  52.             channel.connect();  
  53.         } catch (JSchException e) {  
  54.             LOG.info("getSftp exception:", e);  
  55.         }  
  56.         return (ChannelSftp) channel;  
  57.     }  
  58.         public void disconnect() throws Exception {  
  59.             if (sftp != null) {  
  60.                if (sftp.isConnected()) {  
  61.                     sftp.disconnect();  
  62.                } else if (sftp.isClosed()) {  
  63.                     System.out.println("Session close...........");  
  64.                }  
  65.             }  
  66.         }  
  67. }  

 2:SFTP上传单个文件

  1. /**  
  2.      * SFTP上传单个文件  
  3.      *   
  4.      * @Title: upload  
  5.      * @param directory  
  6.      * @param uploadFile  
  7.      * @throws Exception  
  8.      *             void  
  9.      * @author wangqinghua  
  10.      * @date 2015-9-24 下午1:49:55  
  11.      */  
  12.     public void upload(String directory, String uploadFile) throws Exception {  
  13.         sftp.cd(directory);  
  14.         File file = new File(uploadFile);  
  15.         sftp.put(new FileInputStream(file), file.getName());  
  16.     }  


3.上传目录下的所有文件(批量上传)

  1. /**  
  2.      * 上传目录下的所有文件(批量上传)  
  3.      *   
  4.      * @Title: uploadByDirectory  
  5.      * @param directory  
  6.      * @throws Exception  
  7.      *             void  
  8.      * @author wangqinghua  
  9.      * @date 2015-9-24 下午1:50:53  
  10.      */  
  11.     public void uploadByDirectory(String directory) throws Exception {  
  12.         String uploadFile = "";  
  13.         List<String> uploadFileList = this.listFiles(directory);  
  14.         Iterator<String> it = uploadFileList.iterator();  
  15.         while (it.hasNext()) {  
  16.             uploadFile = it.next().toString();  
  17.             this.upload(directory, uploadFile);  
  18.         }  
  19.     }  

4:通过SFTP下载文件

  1. /**  
  2.      * 通过SFTP下载文件  
  3.      *   
  4.      * @Title: download  
  5.      * @param directory  
  6.      * @param downloadFile  
  7.      * @param saveDirectory  
  8.      * @throws Exception  
  9.      *             void  
  10.      * @author wangqinghua  
  11.      * @date 2015-9-24 下午1:56:22  
  12.      */  
  13.     public void download(String directory, String downloadFile,  
  14.             String saveDirectory) throws Exception {  
  15.         String saveFile = saveDirectory + "//" + downloadFile;  
  16.         sftp.cd(directory);  
  17.         File file = new File(saveFile);  
  18.         sftp.get(downloadFile, new FileOutputStream(file));  
  19.     }  

5:批量下载目录下的文件


  1. /**  
  2.      * 批量下载目录下的文件  
  3.      *   
  4.      * @Title: downloadByDirectory  
  5.      * @param directory  
  6.      * @param saveDirectory  
  7.      * @throws Exception  
  8.      *             void  
  9.      * @author wangqinghua  
  10.      * @date 2015-9-24 下午1:58:17  
  11.      */  
  12.     public void downloadByDirectory(String directory, String saveDirectory)  
  13.             throws Exception {  
  14.         String downloadFile = "";  
  15.         List<String> downloadFileList = this.listFiles(directory);  
  16.         Iterator<String> it = downloadFileList.iterator();  
  17.         while (it.hasNext()) {  
  18.             downloadFile = it.next().toString();  
  19.             if (downloadFile.toString().indexOf(".") < 0) {  
  20.                 continue;  
  21.             }  
  22.             this.download(directory, downloadFile, saveDirectory);  
  23.         }  
  24.     }  

6:删除文件

  1. /**  
  2.      * 删除文件  
  3.      *   
  4.      * @Title: delete  
  5.      * @param directory  
  6.      * @param deleteFile  
  7.      * @throws Exception  
  8.      *             void  
  9.      * @author wangqinghua  
  10.      * @date 2015-9-24 下午1:58:57  
  11.      */  
  12.     public void delete(String directory, String deleteFile) throws Exception {  
  13.         sftp.cd(directory);  
  14.         sftp.rm(deleteFile);  
  15.     }  

7:文件重命名

  1. /**  
  2.      * 文件重命名  
  3.      *   
  4.      * @Title: rename  
  5.      * @param directory  
  6.      * @param oldFileNm  
  7.      * @param newFileNm  
  8.      * @throws Exception  
  9.      *             void  
  10.      * @author wangqinghua  
  11.      * @date 2015-9-24 下午2:02:22  
  12.      */  
  13.     public void rename(String directory, String oldFileNm, String newFileNm)  
  14.             throws Exception {  
  15.         sftp.cd(directory);  
  16.         sftp.rename(oldFileNm, newFileNm);  
  17.     }  

8:获得文件流

  1. /**  
  2.      * 获得文件流  
  3.      *   
  4.      * @Title: get  
  5.      * @param directory  
  6.      * @return  
  7.      * @throws Exception  
  8.      *             InputStream  
  9.      * @author wangqinghua  
  10.      * @date 2015-9-24 下午2:03:41  
  11.      */  
  12.     public InputStream getInputStream(String directory) throws Exception {  
  13.         InputStream streatm = sftp.get(directory);  
  14.         return streatm;  
  15.     }  

9:Servlet结合SFTP实现简单的文件下载


  1. /**  
  2.      * Servlet结合SFTP实现简单的文件下载  
  3.      * @Title: doPost  
  4.      * @param request  
  5.      * @param response  
  6.      * @throws IOException  
  7.      * @throws ServletException  
  8.      * void  
  9.      * @author wangqinghua   
  10.      * @date 2015-9-24 下午2:15:40  
  11.      */  
  12.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  13.             throws IOException, ServletException {  
  14.         LOG.info("进入下载文件开始..........");  
  15.         String host = "";// 主机地址  
  16.         String port = "";// 主机端口  
  17.         String username = "";// 服务器用户名  
  18.         String password = "";// 服务器密码  
  19.         String planPath = "";// 文件所在服务器路径  
  20.         BufferedInputStream bis = null;  
  21.         BufferedOutputStream bos = null;  
  22.         OutputStream fos = null;  
  23.   
  24.         String fileName = "demo";  
  25.         SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");  
  26.         String currentDate = formatter.format(new Date());  
  27.         // demo20150924.txt  
  28.         String downloadFile = fileName + currentDate + ".zip";  
  29.   
  30.         PrintWriter out = null;  
  31.         SftpUtil sftpUtil = new SftpUtil(host, Integer.parseInt(port),  
  32.                 username, password);  
  33.         try {  
  34.             ChannelSftp sftp=sftpUtil.getSftp();  
  35.             String filename = "";  
  36.             // String[] strs=planUrl.split("/");  
  37.             String filePath = planPath;  
  38.             // 列出目录下的文件  
  39.             List<String> listFiles = listFiles(filePath);  
  40.             boolean isExists = listFiles.contains(downloadFile);  
  41.             if (isExists) {  
  42.                 sftp.cd(filePath);  
  43.                 if (sftp.get(downloadFile) != null) {  
  44.                     bis = new BufferedInputStream(sftp.get(downloadFile));  
  45.                 }  
  46.                 filename = downloadFile;  
  47.                 fos = response.getOutputStream();  
  48.                 bos = new BufferedOutputStream(fos);  
  49.                 response.setCharacterEncoding("UTF-8");  
  50.                 response.setContentType("application/x-msdownload;charset=utf-8");  
  51.                 final String agent = request.getHeader("User-Agent");  
  52.                 String attachment = "attachment;fileName=";  
  53.                 String outputFilename = null;  
  54.   
  55.                 if (agent.indexOf("Firefox") > 0) {  
  56.                     attachment = "attachment;fileName*=";  
  57.                     outputFilename = "=?UTF-8?B?"  
  58.                             + (new String(Base64.encodeBase64(filename  
  59.                                     .getBytes("UTF-8")))) + "?=";  
  60.                     ;  
  61.                 } else {  
  62.                     if (agent.indexOf("MSIE") != -1) {  
  63.                         outputFilename = new String(filename.getBytes("gbk"),"iso8859-1");  
  64.                     } else {  
  65.                         outputFilename = new String(filename.getBytes("UTF-8"), "iso8859-1");  
  66.                     }  
  67.                 }  
  68.                 response.setHeader("Content-Disposition", attachment + outputFilename);  
  69.                 int bytesRead = 0;  
  70.                 // 输入流进行先读,然后用输出流去写,下面用的是缓冲输入输出流  
  71.                 byte[] buffer = new byte[8192];  
  72.                 while ((bytesRead = bis.read(buffer)) != -1) {  
  73.                     bos.write(buffer, 0, bytesRead);  
  74.                 }  
  75.                 bos.flush();  
  76.                 LOG.info("文件下载成功");  
  77.             } else {  
  78.                 response.setCharacterEncoding("utf-8");  
  79.                 response.setContentType("text/html; charset=UTF-8");  
  80.                 out = response.getWriter();  
  81.                 out.println("<html >" + "<body>" + "没有找到你要下载的文件" + "</body>"  
  82.                         + "</html>");  
  83.             }  
  84.         } catch (Exception e) {  
  85.             response.setCharacterEncoding("utf-8");  
  86.             response.setContentType("text/html; charset=UTF-8");  
  87.             out = response.getWriter();  
  88.             out.println("<html >" + "<body>" + "没有找到你要下载的文件" + "</body>"  
  89.                     + "</html>");  
  90.         } finally {  
  91.             try {  
  92.                 sftp.disconnect();  
  93.                 LOG.info("SFTP连接已断开");  
  94.             } catch (Exception e) {  
  95.                 e.printStackTrace();  
  96.             }  
  97.   
  98.             if (out != null) {  
  99.                 out.close();  
  100.             }  
  101.             LOG.info("out已关闭");  
  102.             if (bis != null) {  
  103.                 bis.close();  
  104.             }  
  105.             LOG.info("bis已关闭");  
  106.             if (bos != null) {  
  107.                 bos.close();  
  108.             }  
  109.             LOG.info("bos已关闭");  
  110.         }  
  111.     }  

10:获得目录下的所有文件名

  1. /**  
  2.      * 获得目录下的所有文件名  
  3.      *   
  4.      * @Title: listFiles  
  5.      * @param directory  
  6.      * @return  
  7.      * @throws Exception  
  8.      *             List<String>  
  9.      * @author wangqinghua  
  10.      * @date 2015-9-24 下午1:53:40  
  11.      */  
  12.     @SuppressWarnings("rawtypes")  
  13.     public List<String> listFiles(String directory) throws Exception {  
  14.         Vector fileList;  
  15.         List<String> fileNameList = new ArrayList<String>();  
  16.         fileList = sftp.ls(directory);  
  17.         Iterator it = fileList.iterator();  
  18.         while (it.hasNext()) {  
  19.             String fileName = ((LsEntry) it.next()).getFilename();  
  20.             if (".".equals(fileName) || "..".equals(fileName)) {  
  21.                 continue;  
  22.             }  
  23.             fileNameList.add(fileName);  
  24.         }  
  25.         return fileNameList;  
  26.     }  

关于sftp内部方法详情:http://blog.csdn.net/jr_soft/article/details/18704857


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约