• Java常用文件操作-2


      上篇文章记录了常用的文件操作,这里记录下通过SSH服务器操作Linux服务器的指定路径下的文件。

    这里用到了第三方jar包 jsch-0.1.53.jar, jsch-api

    1、删除服务器上指定路径下的所有文件(包括本目录)-经测试,在Linux下运行,没有问题

     1 /**
     2      * 删除
     3     *@param dst
     4     *@param sftpUtil
     5     *@return
     6     *@author qin_hqing
     7     *@date 2015年7月6日 下午4:45:31
     8     *@comment
     9      */
    10     protected static boolean removeFileFromSSH(String dst, ChannelSftp chanSftp) {
    11         boolean bl = false;
    12         
    13         try {
    14             chanSftp.cd(dst);
    15             @SuppressWarnings("unchecked")
    16             Vector<LsEntry> v = chanSftp.ls(dst);
    17             if (v.size() == 2) { //空文件夹 直接删除
    18                 chanSftp.rmdir(dst);
    19             }else {
    20                 int delSize = 0;
    21                 for (Iterator<LsEntry> iterator = v.iterator(); iterator.hasNext();) {
    22                     
    23                     LsEntry lsEntry = (LsEntry) iterator.next();
    24                     String ffName = lsEntry.getFilename();
    25                     if (ffName.indexOf(".")>0) { // file 
    26                         chanSftp.rm(ffName); //删除文件
    27                     }else if(ffName.indexOf(".") == -1) {
    28                         removeFileFromSSH(dst+ffName+File.separator, chanSftp); //如果路径有问题可以试着把 File.separator 改成 "/"试试
    29                         chanSftp.cd(dst);
    30                     }
    31                     
    32                     if (delSize == v.size()-1) { //当前文件夹下还存在文件夹
    33                         removeFileFromSSH(dst, chanSftp);
    34                     }
    35                     delSize ++;
    36                 }
    37             }
    38             
    39             bl = true;
    40         } catch (SftpException e) {
    41             e.printStackTrace();
    42         }
    43         
    44         return bl;
    45     }

     2、上传文件到服务器

      A)这里我们用到了一个工具类,该工具类主要功能是通过SSH连接到Linux服务器,释放资源,在服务器上创建路径,代码如下:

      1 package fileUtil;
      2 
      3 import java.io.File;
      4 import java.util.ArrayList;
      5 import java.util.List;
      6 import java.util.Map;
      7 import java.util.Properties;
      8 import java.util.Vector;
      9 
     10 import org.apache.log4j.Logger;
     11 
     12 import com.jcraft.jsch.Channel;
     13 import com.jcraft.jsch.ChannelSftp;
     14 import com.jcraft.jsch.JSch;
     15 import com.jcraft.jsch.JSchException;
     16 import com.jcraft.jsch.Session;
     17 import com.jcraft.jsch.SftpException;
     18 
     19 /**
     20  * @包名 util.sftp
     21  * @文件名 SFTPChannelUtil.java
     22  * @作者 Edi_Kai
     23  * @创建日期 2015年7月3日
     24  * @版本 V 1.0
     25  * @描述
     26  */
     27 public class SFTPChannelUtil {
     28 
     29     private static final Logger LOG = Logger.getLogger(SFTPChannelUtil.class);
     30     
     31     Session session = null;
     32     Channel channel = null;
     33     List<File> list = new ArrayList<File>();
     34 
     35     private static SFTPChannelUtil util;
     36 
     37     public static SFTPChannelUtil getSftpChannelUtil() {
     38         if (null == util) {
     39             util = new SFTPChannelUtil();
     40         }
     41         return util;
     42     }
     43 
     44     /**
     45      * 获取ChannelSftp连接
     46     *@param sftpDetails
     47     *@param timeout
     48     *@return
     49     *@throws JSchException
     50     *@author Edi_Kai
     51     *@date 2015年7月3日 下午5:26:41
     52     *@comment
     53      */
     54     public ChannelSftp getChannel(Map<String, String> sftpDetails, int timeout)
     55             throws JSchException {
     56 
     57         String ftpHost = sftpDetails.get(SFTPConstants.SFTP_REQ_HOST);
     58         String ftpPort = sftpDetails.get(SFTPConstants.SFTP_REQ_PORT);
     59         String ftpUserName = sftpDetails.get(SFTPConstants.SFTP_REQ_USERNAME);
     60         String ftpPassword = sftpDetails.get(SFTPConstants.SFTP_REQ_PASSWORD);
     61 
     62         JSch jsch = new JSch(); // 创建JSch对象
     63         session = jsch.getSession(ftpUserName, ftpHost, Integer.parseInt(ftpPort)); // 根据用户名,主机ip,端口获取一个Session对象
     64         LOG.debug("Session created.");
     65         if (ftpPassword != null) {
     66             session.setPassword(ftpPassword); // 设置密码
     67         }
     68         Properties config = new Properties();
     69         config.put("StrictHostKeyChecking", "no");
     70         session.setConfig(config); // 为Session对象设置properties
     71         session.setTimeout(timeout); // 设置timeout时间
     72         session.connect(); // 通过Session建立链接
     73         LOG.debug("Session connected.");
     74 
     75         LOG.debug("Opening Channel.");
     76         channel = session.openChannel("sftp"); // 打开SFTP通道
     77         channel.connect(); // 建立SFTP通道的连接
     78         LOG.debug("Connected successfully to ftpHost = " + ftpHost
     79                 + ",as ftpUserName = " + ftpUserName + ", returning: "
     80                 + channel);
     81         return (ChannelSftp) channel;
     82     }
     83 
     84     /**
     85      * 关闭连接
     86     *@throws Exception
     87     *@author Edi_Kai
     88     *@date 2015年7月3日 下午5:27:02
     89     *@comment
     90      */
     91     public void closeChannel() throws Exception {
     92         if (channel != null) {
     93             channel.disconnect();
     94         }
     95         if (session != null) {
     96             session.disconnect();
     97         }
     98     }
     99 
    100     /**
    101      * 查看服务器上是否存在该目录,如果不存在则创建
    102     *@param dir
    103     *@param channelSftp
    104     *@author Edi_Kai
    105     *@date 2015年7月3日 下午5:07:25
    106     *@comment
    107      */
    108     public void createDir(String dir, ChannelSftp channelSftp) {
    109         String parDir = dir.substring(0, dir.lastIndexOf("/"));
    110         try {
    111             Vector<?> content = channelSftp.ls(dir);
    112             
    113             if (content == null) {
    114                 createDir(parDir, channelSftp);
    115                 if (dir.indexOf(".")<0) {
    116                     channelSftp.mkdir(dir);
    117                 }
    118             }
    119         } catch (SftpException e) {
    120             try {
    121                 createDir(parDir, channelSftp);//如果报异常,则说明dir路径不存在,则创建该路径
    122                 if (dir.indexOf(".")<0) {
    123                     channelSftp.mkdir(dir);
    124                 }
    125             } catch (SftpException e1) {
    126                 e1.printStackTrace();
    127             }
    128         }
    129     }
    130 }

      该类中用到了一个存放常量参数的配置类,SFTPConstants.java,代码如下

    package fileUtil;
    
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * @包名 util.sftp
     * @文件名 SFTPConstants.java
     * @作者 Edi_Kai
     * @创建日期 2015年7月3日
     * @版本 V 1.0
     * @描述
     */
    public class SFTPConstants {
       public static final String SFTP_REQ_HOST = "host"; public static final String SFTP_REQ_PORT = "port"; public static final String SFTP_REQ_USERNAME = "username"; public static final String SFTP_REQ_PASSWORD = "password"; /** * 获取Linux服务器 登录信息 *@return *@author Edi_Kai *@date 2015年7月3日 下午5:23:37 *@comment */ public static Map<String, String> getConfig() { Map<String, String> cfg = new HashMap<String, String>(); cfg.put(SFTP_REQ_HOST, FileUtil.getPropValue("sshServerHost"));//192.168.1.110 cfg.put(SFTP_REQ_PORT, FileUtil.getPropValue("sshServerPort"));//22 cfg.put(SFTP_REQ_USERNAME, FileUtil.getPropValue("sshServerUN")); cfg.put(SFTP_REQ_PASSWORD, FileUtil.getPropValue("sshServerPwd")); return cfg; } }

      B)、上传文件到服务器

    /**
         * 将本服务器上的文件上传到SSH服务器的指定路径下
        *@param src 本地服务器文件路径
        *@param dst SSH服务器路径
        *@return
        *@author Edi_Kai
        *@date 2015年7月6日 上午11:58:30
        *@comment
         */
        public static boolean upFile2SSHServer(String src, String dst) {
            boolean bl = false;
            SFTPChannelUtil util = SFTPChannelUtil.getSftpChannelUtil();
            try {
                ChannelSftp chanSftp = util.getChannel(SFTPConstants.getConfig(), 10000);
    
                List<File> list = FileUtil.getAllFile(src);
                for (int i = 0; i < list.size(); i++) {
                    String path = list.get(i).getPath();
    
                    path = path.replaceAll("\\", "/");// E:/ad4/css/ad.css
                    if (path.indexOf(":")>-1) {
                        path = path.split(":")[1].substring(1);// ad4/css/ad.css
                    }
                 
                    util.createDir(dst, chanSftp);
                    
                    chanSftp.put(list.get(i).getPath(), serverPath);
                }
    
                bl = true;
            } catch (JSchException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                try {
                    util.closeChannel();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return bl;
        }

     如有遗漏,继续追加....

    /**************************************************************/

      每天多学一点....

    /**************************************************************/

  • 相关阅读:
    Tjoi 2017 异或和
    Noi 十连测 建造记者站
    Noi 十连测 基因改造计划
    Noi 十连测 人生的经验
    NOI 十连测 Round 5 T2 运河计划
    NOI 十连测 Round 5 T1
    【ZJOI2018】迷宫
    BZOJ 十连测 day5 T3
    BZOJ 十连测 可持久化字符串
    BZOJ 十连测 二进制的世界
  • 原文地址:https://www.cnblogs.com/edi-kai/p/4702636.html
Copyright © 2020-2023  润新知