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);
     }
 }
时间: 2024-08-02 02:42:07

FTP 上传下载工具类的相关文章

java ftp 上传下载工具类

1 package com.mohecun.utils; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileNotFoundException; 6 import java.io.FileOutputStream; 7 import java.io.IOException; 8 import java.io.InputStream; 9 import java.io.OutputStre

高可用的Spring FTP上传下载工具类(已解决上传过程常见问题)

前言 最近在项目中需要和ftp服务器进行交互,在网上找了一下关于ftp上传下载的工具类,大致有两种. 第一种是单例模式的类. 第二种是另外定义一个Service,直接通过Service来实现ftp的上传下载. 这两种感觉都有利弊. 第一种实现了代码复用,但是配置信息全需要写在类中,维护比较复杂. 第二种如果是spring框架,可以通过propertis文件,动态的注入配置信息,但是又不能代码复用. 所以我打算自己实现一个工具类,来把上面的两种优点进行整合.顺便把一些上传过程中一些常见的问题也给解

android 网络文件上传下载工具类总结

1.获取文件的最后修改时间 @SuppressLint("SimpleDateFormat") public String getFileDataTime(File file) { Date date = new Date(file.lastModified()); SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 24小时制 String LgTime = sdfo

简单的FTP上传下载(java实现)

/** *阅读前请自己在win7上建立FTP主机 *具体步骤如:http://jingyan.baidu.com/article/574c5219d466c36c8d9dc138.html * 然后将以下FTP,username,password分别改成你的FTP ip地址 用户名 密码即可 * 本例子用了apche的commons-net-3.3.jar以方便FTP的访问 请手动buid -path * 待完成版 刷新按钮 登录 都还没有做 而且上传 下载 完成后都需要重新运行 * 2014-

python之实现ftp上传下载代码(含错误处理)

# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之实现ftp上传下载代码(含错误处理) #http://www.cnblogs.com/kaituorensheng/p/4480512.html#_label2 import ftplib import socket import os def ftpconnect(ftp_info): try: ftp = ftplib.FTP(ftp_info[0]) except (socket.er

python之模块ftplib(实现ftp上传下载代码)

# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之模块ftplib(实现ftp上传下载代码) #需求:实现ftp上传下载代码(不含错误处理) from ftplib import FTP def ftpconnect(): ftp_server='ftp.python.org' ftp=FTP() ftp.set_debuglevel(2)#打开调式级别2 ftp.connect(ftp_server,21) ftp.login('',''

python网络编程socket模块实现ftp上传下载

本实验实现ftp上传文件下载文件功能,并具有校验文件完整性,打印进度条功能, 主要练习socket,struct模块. ftp用户文件存放在user.json文件中 user.json文件内容 {"lisi": "abcdef", "hyh": "123456"} ftp客户端脚本ftpclient.py #!/usr/bin/python # --*-- coding: utf-8 --*-- import socket i

windows下ftp上传下载和一些常用命令

先假设一个ftp地址 用户名 密码 FTP Server: home4u.at.china.com User: yepanghuang Password: abc123 打开windows的开始菜单,执行“运行”命令,在对话框中输入ftp,按下“确定”按钮将会切换至DOS窗口,出现命令提示符 ftp>键入命令连接FTP服务器: ftp> open home4u.at.china.com (回车) 稍等片刻,屏幕提示连接成功: ftp> connected to home4u.china.

验证码确保php无输出、sql语句的封装性、文件上传的工具类【这三个重点工具类实现】

1.php代码在引入中不会进行结束或者确保结束之后没有空格,来保证php在被包含中没有被输出[防止header和session_start()对输出的控制]实质上,需要注意的就是,要不就进行输出缓存控制以及php开始标签前没有空格 验证码这个功能需要header和session两个功能[尤其需要注意输出的问题] [总结:防止php代码中带着一些输出的问题](1)在php标签中开始<?php 前顶格(2)php结束符要不不写,写了就不要在结束之后还有换行[防止该文件被包含之后提前出线输出](3)或