FTP 上传下载工具类

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

 import org.apache.commons.net.ftp.FTPClient;
 import org.apache.commons.net.ftp.FTPFile;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;

 /**
  * @khj
  * @title FtpUtils
  * @Description : FTP 上传下载工具类
 * @time
  */
 public class FTPUtils
 {
     /**
      * 日志
     */
     private static Logger logger = LoggerFactory.getLogger(FTPUtils.class);
     
     private static FTPClient ftp;
     
     /**
      * 连接ftp <一句话功能简述> <功能详细描述>
      * 
      * @param addr
      * @param port
      * @param username
      * @param password
      * @return
      * @see [类、类#方法、类#成员]
      */
     public static boolean connect(String addr, int port, String username, String password)
     {
         ftp = new FTPClient();
         
         try
         {
             ftp.connect(addr, 21);
             ftp.login(username, password);
             
         }
         catch (SocketException e)
         {
             e.printStackTrace();
         }
         catch (IOException e)
         {
             e.printStackTrace();
         }
         return ftp.isConnected();
     }
     
     @SuppressWarnings("unused")
     private void upload(File file, String path)
     {
         logger.info(" file.isDirectory() : {}" + file.isDirectory());
         
         try
         {
             if (file.isDirectory())
             {
                 ftp.makeDirectory(file.getName());
                 ftp.changeWorkingDirectory(file.getName());
                 String[] files = file.list();
                 for (int i = 0; i < files.length; i++)
                 {
                     File file1 = new File(file.getPath() + "\\" + files[i]);
                     if (file1.isDirectory())
                     {
                         upload(file1, path);
                         ftp.changeToParentDirectory();
                     }
                     else
                     {
                         File file2 = new File(file.getPath() + "\\" + files[i]);
                         FileInputStream input = new FileInputStream(file2);
                         ftp.storeFile(file2.getName(), input);
                         input.close();
                     }
                 }
             }
             else
             {
                 File file2 = new File(file.getPath());
                 
                 System.out.println(" file.getPath() : " + file.getPath() + " | file2.getName() : " + file2.getName());
                 
                 InputStream input = new FileInputStream(file2);
                 
                 ftp.changeWorkingDirectory(path);
                 ftp.storeFile(file2.getName(), input);
                 
                 input.close(); // 关闭输入流
                ftp.logout(); // 退出连接
            }
         }
         catch (Exception e)
         {
             logger.error(e.getMessage());
         }
     }
     
     @SuppressWarnings("static-access")
     public static byte[] downloadFile(String fileName)
     {
         byte[] bytes = null;
         try
         {
             ftp.changeWorkingDirectory("");
             
             // 列出该目录下所有文件
            FTPFile[] fs = ftp.listFiles(fileName);
             
             // 遍历所有文件,找到指定的文件
            for (FTPFile file : fs)
             {
                 if (file.getName().equals(fileName))
                 {
                     // 根据绝对路径初始化文件
                    // File localFile = new File(localPath);
                     // if (!localFile.exists())
                     // {
                     // localFile.createNewFile();
                     // }
                     // // 输出流
                    // OutputStream os = new FileOutputStream(localFile);
                     InputStream in = null;
                     // 下载文件
                    ftp.setBufferSize(1024);
                     ftp.setControlEncoding("UTF-8");
                     ftp.setFileType(ftp.BINARY_FILE_TYPE);
                     // 下载文件到 localFile
                     // ftp.retrieveFile(ff.getName(), os);
                     
                     String remoteAbsoluteFile = file.getName();
                     remoteAbsoluteFile = new String(remoteAbsoluteFile.getBytes("UTF-8"), "ISO-8859-1");
                     in = ftp.retrieveFileStream(remoteAbsoluteFile);
                     
                     bytes = input2byte(in);
                 
                     System.out.println("下载成功!" + bytes.length);
                     
                     in.close();
                 }
             }
             
             ftp.logout(); // 退出连接
        }
         catch (Exception e)
         {
             e.printStackTrace();
         }
         return bytes;
     }
     
     /**
      * byte[] 转 file 
      * 
      * @param bytes
      * @param path
      * @return
      * @see [类、类#方法、类#成员]
      */
     public static void byteToFile(byte[] bytes, String path)
     {
         try
         {
             // 根据绝对路径初始化文件
            File localFile = new File(path);
             if (!localFile.exists())
             {
                 localFile.createNewFile();
             }
             // 输出流
            OutputStream os = new FileOutputStream(localFile);
             
             os.write(bytes);
             
             os.close();
         }
         catch (Exception e)
         {
             e.printStackTrace();
         }
     }
     
     /**
      * 文件转成 byte[] <一句话功能简述> <功能详细描述>
      * 
      * @param inStream
      * @return
      * @throws IOException
      * @see [类、类#方法、类#成员]
      */
     public static byte[] input2byte(InputStream inStream)
         throws IOException
     {
         ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
         byte[] buff = new byte[100];
         int rc = 0;
         while ((rc = inStream.read(buff, 0, 100)) > 0)
         {
             swapStream.write(buff, 0, rc);
         }
         byte[] in2b = swapStream.toByteArray();
         
         swapStream.close();
         
         return in2b;
     }
     
     public static void getPhoto(String filePath,String localPath)
     {
         FTPUtils.connect(ReadPropertiesUtils.getParamValue("ftp.host"),
             21,
             ReadPropertiesUtils.getParamValue("ftp.username"),
             ReadPropertiesUtils.getParamValue("ftp.password"));
         logger.info("");
         byte[] bytes = FTPUtils.downloadFile(filePath);
         
         FTPUtils.byteToFile(bytes, localPath);
     }
     
     public static byte[] getPhoto(String filePath)
     {
         FTPUtils.connect(ReadPropertiesUtils.getParamValue("ftp.host"),
             21,
             ReadPropertiesUtils.getParamValue("ftp.username"),
             ReadPropertiesUtils.getParamValue("ftp.password"));
         logger.info("");
         byte[] bytes = FTPUtils.downloadFile(filePath);
         
         //FTPUtils.byteToFile(bytes, localPath);
         return bytes;
     }
     
     public static void main(String[] args)
         throws Exception
     {
         
         String filePath = "T_ZDRY_IDX_JXXX_INC/010020090902731604.jpg";
         
         String localPath = "d:\\ccc.jpg";
         
         FTPUtils.getPhoto(filePath, localPath);
     }
 }

 

posted on 2016-04-08 13:02  火玉  阅读(1008)  评论(0编辑  收藏  举报