zoukankan      html  css  js  c++  java
  • SFTP和FTP的下载和上传

    SFTP:

    获取连接:

    public class SFTPChannel {
        
        private static final Logger log = LoggerFactory.getLogger(SFTPChannel.class);
        
        private static final int SFTP_DEFAULT_TIMEOUT = 60000; //sftp链接默认超时时间为60s
        
        private Session session = null;
        
        private Channel channel = null;
        
        /**
         * 获取sftp通道连接
         * @param host 主机ip
         * @param port 主机端口
         * @param username sftp用户名
         * @param password sftp密码
         * @return
         * @throws JSchException 
         */
        public ChannelSftp connect(String host,int port,String username, String password) throws JSchException
        {
            
            JSch jsch = new JSch(); // 创建JSch对象
            session = jsch.getSession(username, host, port); // 根据用户名,主机ip,端口获取一个Session对象
            log.info("Session created.sftp://:{}:{}@{}:{}",username,password,host,port);
            if (password != null)
            {
                session.setPassword(password); // 设置密码
            }
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config); // 为Session对象设置properties
            session.setTimeout(SFTP_DEFAULT_TIMEOUT); // 设置timeout时间
            session.connect(); // 通过Session建立链接
            log.info("Session connected.");
    
            log.info("Opening Channel.");
            channel = session.openChannel("sftp"); // 打开SFTP通道
            channel.connect(); // 建立SFTP通道的连接
            log.info("Connected successfully to ftpHost = {},as ftpUserName = {}, returning: " + channel,host,port);
            return (ChannelSftp) channel;
        }

    进行下载:

        /**
         * sftp文件下载
         * @param sftp sftp通道
         * @param directory sftp下载目录
         * @param downloadFileName sftp下载的文件名
         * @param savePath sftp文件保存的路径
         * @throws Exception
         */
        public static void download(ChannelSftp sftp,String directory,String downloadFileName,String savePath) throws Exception
        {
            File file = new File(savePath);
            if (!file.exists())
            {
                file.mkdirs();
            }
            log.info("保存的文件路径:{}",savePath);
            log.info("sftp服务器文件的路径:{}" , directory);
            FileOutputStream ous = null;
            try {
                ous = new FileOutputStream(savePath+ File.separator + downloadFileName);
                sftp.cd(directory);//切换到服务器目录
                sftp.get(downloadFileName, ous);
                log.info("下载文件{}成功!",downloadFileName);
            } catch (FileNotFoundException e) {
                log.info(e.getMessage(),e);
            } catch (SftpException e) {
                log.info("下载文件{}失败!",downloadFileName);
                log.info(e.getMessage(),e);
                throw new Exception("服务器上的文件:" + downloadFileName + "没有获取到!");
                /*File file2 = new File(savePath+ File.separator + downloadFileName);
                if(file2.exists() && file2.isFile() && file2.length()==0)
                    if(!file2.delete())
                    {
                        log.error("请关闭使用该文件的所有进程或者流!!",e);
                    }
                    else
                    {
                        log.info("文件大小为:"+file2.length()+"字节的文件:"+file2.getName()+"已经被成功删除!!");
                    }*/
            } finally {
                    ous.close();
                    //sftp.quit();
            }
        }

     controller层的代码:

       public void dwAlipayBill() {
            long begintime = System.currentTimeMillis();
            DateBean dateBean = new DateBean();
            String date = dateBean.getYesterdayDate("");
            //date = "20151103";
            String fileName = pid + "_" + date + ".zip";
            SFTPChannel channel = new SFTPChannel();
            ChannelSftp chsftp = null;
            File file = new File(alipay_sftp_savepath + date + File.separator + fileName);
            if (!file.exists()) {
                try {
                    chsftp = channel.connect(alipay_sftp_ip, alipay_sftp_port, alipay_sftp_username, alipay_sftp_password);
                    SFTPUtils.download(chsftp, alipay_sftp_path + "download/" + date, fileName, alipay_sftp_savepath + date);
                } catch (JSchException e) {
                    log.error("sftp登录异常", e);
                } catch (Exception e) {
                    log.error(e.getMessage(),e);
                } finally {
                    chsftp.quit();
                    channel.closeChannel();
                }
            } else {
                log.error("{}文件已经存在,不需要重复下载!!", fileName);
            }
            //文件下载失败时删除临时创建的空文件
            //File file = new File(alipay_sftp_savepath + date + File.separator + fileName);
            if (file.exists() && file.isFile() && file.length() == 0)
                if (!file.delete()) {
                    log.error("请关闭使用该文件的所有进程或者流!!");
                } else {
                    log.info("文件大小为:" + file.length() + "字节的文件:" + file.getName() + "已经被成功删除!!");
                }
            long endtime = System.currentTimeMillis();
            log.info("{}的支付宝对账单下载成功,用时{}毫秒。", date, (endtime - begintime));
        }

     如何直接读取zip文件里的内容:

                    String path = "D:\sasa.zip";
                    ZipFile zf = new ZipFile(path);
                   // new BufferedInputStream(new FileInputStream(path));
                    InputStream in = new BufferedInputStream(new FileInputStream(path));
                    Charset gbk = Charset.forName("gbk");
                    ZipInputStream zin = new ZipInputStream(in,gbk);
                    ZipEntry ze;
                    while((ze = zin.getNextEntry()) != null){
                        if(ze.toString().endsWith("txt")){
                            BufferedReader br = new BufferedReader(
                                    new InputStreamReader(zf.getInputStream(ze)));
                            String line;
                            while((line = br.readLine()) != null){
                                System.out.println(line.toString());
                            }
                            br.close();
                        }
                        System.out.println();
                    }
                    zin.closeEntry();

    1 读取zip文件,可以通过ZipFile来读取。如果需要读取zip文件内部的一个一个文件。有两种方法。第一种是得到枚举。通过循环来读取

    如:ZipFile zip=new ZipFile(new File(fileName));
    Enumeration enumeration=zip.entries();//通过entries()循环来得到。
    while(enumeration.hasMoreElements()){
    ZipEntry zipEntry=(ZipEntry)enumeration.nextElement();
    System.out.println(zipEntry.getName());
    }
    
    
    2 也可以通过getEntry(name)来得到zipEntry对象。
    如:ZipFile zip=new ZipFile(new File(fileName));
    ZipEntry zipEntry=zip.getEntry("channel_system_Chinese.txt");//通过getEntry(name)也可以得到指定的ZipEntry对象。
    if(zipEntry!=null){
    System.out.println("已发现该文件:"+zipEntry.getName());
    }
    
    
    
    
    综述:得到zip文件中的一个个zipEntry对象。可以通过ZipFile的entries()和getEntry(name)这两种来得到。第一种是循环,得到枚举。第二种是得到指定的。
    
    
    完整的例子:
    String fileName="D:\test1.zip";
    new TestMain1().readZipEntry(fileName);
    
    
    public void readZipEntry(String fileName){
    try {
    ZipFile zip=new ZipFile(new File(fileName));
    Enumeration enumeration=zip.entries();
    while(enumeration.hasMoreElements()){
    ZipEntry zipEntry=(ZipEntry)enumeration.nextElement();
    System.out.println(zipEntry.getName());
    }
    
    System.out.println("也可以通道文件名来得到zipEntry对象");
    ZipEntry zipEntry=zip.getEntry("channel_system_Chinese.txt");
    if(zipEntry!=null){
    System.out.println("已发现该文件:"+zipEntry.getName());
    }
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } 
    }

     从ftp下载:

        public static boolean downloadDuocaiBill(String host, int port, String username, String password, String remotePath,
                String date, String localPath) {
            FTPClient ftpClient = new FTPClient();
            try {
                ftpClient.connect(host, port);
                boolean isLoginSuccess = ftpClient.login(username, password);
                if (!isLoginSuccess) {
                    LOGGER.info("FTP登录失败。");
                    return false;
                }
                LOGGER.info("FTP登录成功。");
                
                ftpClient.changeWorkingDirectory(remotePath + File.separator + date);
                FTPFile[] files = ftpClient.listFiles();
                int fileCount = 0;
                File dir = new File(localPath + File.separator + date);
                if(!dir.exists()) {
                    dir.mkdirs();
                }
                for (FTPFile file : files) {
                    String fileName = file.getName();
                    //对账文件名称为:接口编码(80)+YYYYMMDD + 序号(2位,00-47)+文件编号(4位,同一天如果文件太大,会拆分为多个文件).txt
                    if (fileName.startsWith("80" + date + getDuocaiBillFileSeq()) && fileName.endsWith(".txt")) {
                        File localFile = new File(localPath + File.separator + date + File.separator + fileName);
                        OutputStream os = new FileOutputStream(localFile);
                        LOGGER.info("开始下载文件,文件名:{}。", fileName);
                        boolean isSuccess = ftpClient.retrieveFile(fileName, os);
                        os.close();
                        if(isSuccess) {
                            fileCount ++;
                            LOGGER.info("下载文件成功,文件名:{}。", fileName);
                        }else {
                            LOGGER.info("下载文件失败,文件名:{}。", fileName);
                        }
                    }
                }
                ftpClient.logout();
    
                if(fileCount == 0) {
                    LOGGER.info("未找到待下载文件。");
                    return false;
                }else {
                    LOGGER.info("下载文件结束,共下载{}个文件。", fileCount);
                    return true;
                }
            } catch (Exception e) {
                LOGGER.info("下载文件失败,原因:{}。", e.getMessage());
                return false;
            } finally {
                if (ftpClient.isConnected()) {
                    try {
                        ftpClient.disconnect();
                    } catch (IOException ioe) {
                        LOGGER.info("关闭FTP客户端失败,原因:{}。", ioe.getMessage());
                    }
                }
            }
        }
  • 相关阅读:
    第12组 Beta冲刺(2/5)
    第12组 Beta冲刺(1/5)
    第12组 Alpha事后诸葛亮
    第12组 Alpha冲刺(6/6)
    第12组 Alpha冲刺(5/6)
    期末大作业(第十七小组)
    补交:第2次&第5次实践作业
    第6次实践作业 (第17小组)
    第4次实践作业
    第3次实践作业
  • 原文地址:https://www.cnblogs.com/cherishforchen/p/11193230.html
Copyright © 2011-2022 走看看