Java package ftp tool class Daquan

Download file stream (get to io stream file)

package com.kl.print.util;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;


/** 
 * ftp upload and download tool class   
 * @author  wangn
 * @date    January 30, 2018 
 * @version 1.0 
 */  
public class FtpUtils {
     private final static Log logger = LogFactory.getLog(FtpUtils.class);  
     private static FTPClient ftp;
    
     public static FTPClient getFTPClient(String ftpHost, String ftpUserName,  
                String ftpPassword, int ftpPort) {  
            FTPClient ftpClient = new FTPClient();  
            try {  
                ftpClient = new FTPClient();  
                ftpClient.connect(ftpHost, ftpPort);// connect FTP server  
                ftpClient.login(ftpUserName, ftpPassword);// Login to FTP server  
                if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {  
                    logger.info("Not connected to FTP, username or password is incorrect.");  
                    ftpClient. disconnect();  
                } else {  
                    logger.info("FTP connection is successful.");  
                }  
            } catch (SocketException e) {  
                e.printStackTrace();  
                logger.info("FTP IP address may be wrong, please configure it correctly." );  
            } catch (IOException e) {  
                e.printStackTrace();  
                logger.info("The FTP port is wrong, please configure it correctly.");   
            }  
            return ftpClient;  
        }  
    /**  
     * Description: Upload files to the FTP server  
     * @param host FTP server hostname  
     * @param port FTP server port  
     * @param username FTP login account  
     * @param password FTP login password  
     * @param filePath FTP server file storage path.
     * @param filename The file name uploaded to the FTP server  
     * @param input input stream  
     * @return Returns true if successful, otherwise returns false  
     */    
    public static boolean uploadFile(String host, int port, String username, String password, String filePath, String path,  
            String filename, InputStream input) {  
        boolean result = false;  
        FTPClient ftp = new FTPClient();  
        try {  
            int reply;  
            ftp.connect(host, port);// Connect to the FTP server  
            // If the default port is used, you can use the ftp.connect(host) method to directly connect to the FTP server  
            ftp.enterLocalPassiveMode();  
            ftp.login( username, password);// Login  
            reply = ftp.getReplyCode();  
            if (!FTPReply.isPositiveCompletion(reply)) {  
                ftp.disconnect();  
                return result;  
            }  
            //Set the type of uploaded file to binary type  
            ftp.setFileType (FTP.BINARY_FILE_TYPE);
            ftp.cwd("/");
            path = path.replaceAll("\\\\", "/");
            String[] paths = path.split("/");
            for (int i = 0; i < paths.length; i++)
            {
                String pathTemp = paths[i];
                
                /* Create parent and child directories*/
                if(!ftp.makeDirectory(pathTemp))
                {
                    System.out.println( "---Create directory failed--");
                }
                
                
                ftp.changeWorkingDirectory(pathTemp);
                
                /* Enter the directory*/
                /*ftp.cwd(pathTemp);
                System.out.println("ftp.cwd(pathTemp) "+ ftp.cwd(pathTemp));
                ftp.storeFile(filename, input);*/
            }
            
           return ftp.storeFile(filename, input);
            //upload file  
           // ftp.makeDirectory(path);  
           /* if (!ftp.storeFile(filename, input)) {  
                return result;  
            }  
            input.close();  
            ftp.logout();  
            result = true;  */
            
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            if (ftp.isConnected()) {  
                try {  
                    ftp.disconnect();  
                } catch (IOException ioe) {  
                }  
            }  
        }  
        return result;  
    } 
     /* 
     * 从FTP服务器下载文件 
     *  
     * @param ftpHost FTP IP address 
     *  
     * @param ftpPassword FTP username and password 
     *  
     * @param ftpPort FTP port 
     *  
     * @param ftpPath FTP server file path format: ftptest/aa 
     *  
     * @param localPath download to the local location Format: H:/download 
     *  
     * @param fileName file name 
     */  
     public static OutputStream downloadFtpFile(String ftpHost, String ftpUserName,  
                String ftpPassword, int ftpPort, String ftpPath,  
                String fileName) {  
      
            FTPClient ftpClient = null;  
            OutputStream os=null;
            try {  
                ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);  
                ftpClient.setControlEncoding("UTF-8"); // Chinese support  
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);  
                ftpClient.enterLocalPassiveMode();  
                ftpClient.changeWorkingDirectory(ftpPath);  
                /*File localFile = new File(localPath + File.separatorChar + fileName);  
                 Determine whether the directory exists, and create it if it does not exist (parent directory) 
                if(!localFile.getParentFile().exists()){
                    localFile.getParentFile(). mkdirs();
                }*/
                 os = new FileOutputStream(fileName);  
                ftpClient.retrieveFile(fileName, os);  
                os.close();  
                ftpClient.logout();  
                return os;
            } catch (FileNotFoundException e) {  
                logger.error("not found" + ftpPath + "file");  
                e.printStackTrace ();  
            } catch (SocketException e) {  
                logger.error("Failed to connect to FTP.");  
                e.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
                logger.error("File read error .");  
                e.printStackTrace();  
            }  
            return null;
        }  

        
         /**
          * @param ip
          * @param port
          * @param userName
          * @param userPwd
          * @param path
          * @throws SocketException
          * @throws IOException function:连接到服务器
          */
         public static  OutputStream downloadFile(String ip, int port, String userName, String userPwd, String path,String fileName) {
             ftp = new FTPClient();
             ByteArrayOutputStream swapStream =null;
          try {
           // 连接
              ftp.connect(ip, port);
           // 登录
              ftp.login(userName, userPwd);
           if (path != null && path.length() > 0) {
               //System.out.println("path:"+path);
            // 跳转到指定目录
               ftp.changeWorkingDirectory(path);
            InputStream ins = null; 
            
             try {  
             ins = ftp.retrieveFileStream(fileName); 
              // System.out.println("ins:"+ins.available());
               
               swapStream= new ByteArrayOutputStream();
                      int ch;
                      while ((ch = ins.read()) != -1) {   
                           swapStream.write(ch);   
                     }
                    // System.out.println("swapStream:"+swapStream.size());
             if(ins != null){  
             ins.close();  
            }  
             
             // 主动调用一次getReply()把接下来的226消费掉. 这样做是可以解决这个返回null问题  
             ftp.getReply();  
             } catch (IOException e) {  
             e.printStackTrace();  
             }  
            
           }
          } catch (SocketException e) {
           e.printStackTrace();
          } catch (IOException e) {
           e.printStackTrace();
          }finally {
              FtpUtils.closeServer();
          }
          return swapStream;
         }

         /**
          * @throws IOException function:关闭连接
          */
         public static void closeServer() {
          if (ftp.isConnected()) {
           try {
               ftp.logout();
               ftp.disconnect();
           } catch (IOException e) {
            e.printStackTrace();
           }
          }
         }
        
        public static void main(String[] args) throws Exception {
            /*String ftpHost = "192.168.0.85";  
            String ftpUserName = "icbc";
            String ftpPassword = "evhAB6#5";  
            int ftpPort = 21;  
            String ftpPath = "/data/ftp/icbc/2017/02/10";  
            //String localPath = "D:/dd/bb"; 
            String  fileName="1708041358198180SW01.pdf";*/
           
            //读取文件的名称,可以通过给定字段进行查询文件
            //FtpUtils.downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, fileName);
           
           // File localFile = new File(localPath + File.separatorChar + fileName);  
            /* 判断目录是否存在,不存在的话创建(父目录) */
             String fileName="1708041358198180SW03.pdf";
              String ip = "192.168.0.85";        // 服务器IP地址
              String userName = "*******";        // 用户名
             String userPwd = "*********";        // 密码
             int port = 21;      // 端口号
             String path = "/2018/02/12";        // 读取文件的存放目录
          OutputStream outputStream= FtpUtils.downloadFile(ip, port, userName, userPwd, path,fileName);
          System.out.println("文件内容为:"+outputStream.toString());
        }
}
 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325724942&siteId=291194637