java使用ftp上传文件示例分享

时间:2021-10-23 08:33:03 


import java.io.ByteArrayInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.net.SocketException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 

import org.apache.commons.io.IOUtils; 
import org.apache.commons.net.ftp.FTPClient; 

/**
 * class name:FTPFileTransmit <BR>
 * class description: please write your description <BR>
 * Remark: <BR>
 * @version 1.00 2011-8-9
 */ 
public class FTPFileTransmit { 

    private String ftpPath; 
    private String ftpName; 
    private String ftpPassword; 
    private String ftpServerIP; 

    public FTPFileTransmit() { 
        this.ftpPath = "xxx/xxx/"; 
        this.ftpName = "name"; 
        this.ftpPassword = "pass"; 
        this.ftpServerIP = "192.168.0.xx"; 
    } 

     
    /**
     * Method name: saveInFTP <BR>
     * Description: 把文件存储在FTP上 <BR>
     * Remark: <BR>
     * @param FolderName            示例"xxx/xxx/"
     * @param FileName              示例"thefilename"
     * @param data                  byte[]数组
     * @return  boolean<BR>
     */ 
    public boolean saveInFTP (String FolderName, String FileName, byte[] data) { 
        boolean flag = false; 

        // 创建FTP客户端  
        FTPClient ftpClient = new FTPClient(); 
        // 输入流用于读取文件  
//      FileInputStream fis = null;  
        ByteArrayInputStream bis = null; 

        try { 
            // 如果FolderName 和 FileName都不符合基本要求, 那么就没有必要进行ftp操作  
            if (FolderName != null 
                    && FolderName.compareTo("") != 0 
                    && FileName != null 
                    && FileName.compareTo("") != 0) { 

                // 建立FTP连接  
                ftpClient.connect(this.ftpServerIP); 

                // 如果登录成功后, 才进行创建输入流  
                if (ftpClient.login(this.ftpName, this.ftpPassword)) { 
//                  File srcClientFile = new File("C:/ParseXML.xml");  

                    // 实例化输入流  
//                  fis = new FileInputStream(srcClientFile);  

                    if (ftpClient.changeWorkingDirectory(FolderName)) { 
                        // 将byte[]写入到输入流中, 实例化  
                        bis = new ByteArrayInputStream(data); 

                        // 设置缓冲  
                        ftpClient.setBufferSize(1024); 

                        // 设置文件类型(二进制类型)  
                        if (ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE)) { 
                            flag = ftpClient.storeFile(FileName, bis); 
                        } 
                    } 
                } 
            } 
        } catch (SocketException e) { 
            e.printStackTrace(); 
            flag = false; 
        } catch (IOException e) { 
            e.printStackTrace(); 
            flag = false; 
        } catch (Exception e) { 
            e.printStackTrace(); 
            flag = false; 
        } finally { 
            try { 
                // 关闭输入流  
                IOUtils.closeQuietly(bis); 
                // 关闭连接  
                ftpClient.disconnect(); 
            } catch (IOException e) { 
                e.printStackTrace(); 
            } 
        } 

        return flag; 
    } 

    /**
     * Method name: getFromFTP <BR>
     * Description: 从FTP上读取文件 <BR>
     * Remark: <BR>
     * @return  boolean<BR>
     */ 
    public boolean getFromFTP () { 
        boolean flag = false; 

        // 创建FTP客户端  
        FTPClient ftpClient = new FTPClient(); 
        // 输出流用于输出文件  
        FileOutputStream fos = null; 

        try { 
            // 建立FTP连接  
            ftpClient.connect(this.ftpServerIP); 
            // 如果登录成功后, 才进行创建输出流  
            if (ftpClient.login(this.ftpName, this.ftpPassword)) { 
                // FTP文件  
                String distinationFile = "/name/xxx/xxx/xxx文件"; 
                // 实例化输出流  
                fos = new FileOutputStream("C:/ParseXML_InFTP.xml"); 

                // 设置缓冲  
                ftpClient.setBufferSize(1024); 

                // 设置文件类型(二进制类型)  
                if (ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE)) { 
                    ftpClient.retrieveFile(distinationFile, fos); 
                    flag = true; 
                } 
            } 
        } catch (SocketException e) { 
            e.printStackTrace(); 
            flag = false; 
        } catch (IOException e) { 
            e.printStackTrace(); 
            flag = false; 
        } catch (Exception e) { 
            e.printStackTrace(); 
            flag = false; 
        } finally { 
            try { 
                // 关闭输出流  
                IOUtils.closeQuietly(fos); 
                // 关闭连接  
                ftpClient.disconnect(); 
            } catch (IOException e) { 
                e.printStackTrace(); 
            } 
        } 

        return flag; 
    } 

    public boolean createDirectory() { 
        boolean flag = false; 

        // 创建FTP客户端  
        FTPClient ftpClient = new FTPClient(); 

        try { 
            // 建立FTP连接  
            ftpClient.connect(this.ftpServerIP); 
            // 如果登录成功后, 才进行操作  
            if (ftpClient.login(this.ftpName, this.ftpPassword)) { 

                // 切换文件路径, 到FTP上的"NNDD3"文件夹下  
                if (this.ftpPath != null && this.ftpPath.compareTo("") != 0 
                        && ftpClient.changeWorkingDirectory(this.ftpPath)) { 
                    SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd"); 
                    String time = f.format(new Date()); 

                    String FolderName = time + "_ReTransmit"; 
                    ftpClient.makeDirectory(FolderName); 
                    flag = true; 
                } 
            } 
        } catch (SocketException e) { 
            e.printStackTrace(); 
            flag = false; 
        } catch (IOException e) { 
            e.printStackTrace(); 
            flag = false; 
        } catch (Exception e) { 
            e.printStackTrace(); 
            flag = false; 
        } finally { 
            try { 
                // 关闭连接  
                ftpClient.disconnect(); 
            } catch (IOException e) { 
                e.printStackTrace(); 
            } 
        } 

        return flag; 
    } 

    public String[] getAllFolderNames () { 
        // 创建FTP客户端  
        FTPClient ftpClient = new FTPClient(); 

        try { 
            // 建立FTP连接  
            ftpClient.connect(this.ftpServerIP); 

            // 如果登录成功后, 才进行操作  
            if (ftpClient.login(this.ftpName, this.ftpPassword)) { 

                // 切换文件路径, 到FTP上的"NNDD3"文件夹下  
                if (this.ftpPath != null && this.ftpPath.compareTo("") != 0 
                        && ftpClient.changeWorkingDirectory(this.ftpPath)) { 
                    // 将当前时间减去2天, 删除的是前两天的数据包  
                    String time = minusTime(); 

                    String[] allNames = ftpClient.listNames(); 

                    String[] temp = new String[allNames.length]; 
                    // 初始化数组  
                    for (int j = 0; j < allNames.length; j ++) { 
                        temp[j] = ""; 
                    } 

                    // 找出要删除文件夹的名称  
                    for (int i = 0; i < allNames.length; i ++) { 
                        if (allNames[i].substring(0, 8).compareTo(time) <= 0) { 
                            temp[i] = allNames[i]; 
                        } 
                    } 

                    return temp; 
                } 
            } 
        } catch (SocketException e) { 
            e.printStackTrace(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } finally { 
            try { 
                // 关闭连接  
                ftpClient.disconnect(); 
            } catch (IOException e) { 
                e.printStackTrace(); 
            } 
        } 

        return null; 
    } 

    /**
     * 
     * Method name: minusTime <BR>
     * Description: 获取钱两天的时间,如2011-8-1的前两天就是2011-7-30 <BR>
     * Remark: <BR>
     * @return  String<BR>
     */ 
    private String minusTime() { 
        SimpleDateFormat df=new SimpleDateFormat("yyyyMMdd");    
        Date d = new Date(); 
        String timeMinus2 = df.format(new Date(d.getTime() - 2 * 24 * 60 * 60 * 1000));    
        return timeMinus2; 
    } 

    public static void main(String[] args) { 
        FTPFileTransmit ftpFileTransmit = new FTPFileTransmit(); 
        ftpFileTransmit.deleteFoldersInFTP(); 

//      boolean flag = ftpFileTransmit.createDirectory();  
//      if (flag) {  
//          System.out.println("****** FTP文件夹创建成功 ******");  
//      }  

//      String FolderName = ftpFileTransmit.ftpPath + "20110809_ReTransmit/";  
//      byte[] data = new byte[1024];  
//      for (int i = 0; i < data.length; i ++) {  
//          data[i] = 'a';  
//      }  
//      boolean flag = ftpFileTransmit.saveInFTP(FolderName, "2011080912345678" ,data);  
//      if (flag) {  
//          System.out.println("****** FTP文件夹创建成功 ******");  
//      }  
    } 
}

标签:java,ftp,上传文件
0
投稿

猜你喜欢

  • java联调生成测试数据工具类方式

    2021-10-12 06:42:17
  • 同时使用@LoadBalanced @RefreshScope注解负载均衡失效分析

    2023-12-07 10:59:24
  • java打印菱形及直角和等腰三角形的方法

    2023-01-08 20:46:55
  • Redis原子计数器incr,防止并发请求操作

    2021-07-03 13:35:15
  • Android Button 自带阴影效果另一种解决办法

    2021-06-07 04:23:02
  • Java消息队列JMS实现原理解析

    2023-05-14 04:02:04
  • Unity3D UGUI实现翻书特效

    2022-03-30 23:02:59
  • android获取ibeacon列表的方法

    2023-01-18 00:57:54
  • Java调用第三方接口示范的实现

    2023-06-27 20:32:10
  • C# 构造函数如何调用虚方法

    2023-05-12 00:08:57
  • HashMap原理及put方法与get方法的调用过程

    2023-10-06 03:53:02
  • Android 隐藏底部虚拟键的两种方法

    2021-07-18 23:24:51
  • Java实现LeetCode(1.两数之和)

    2021-06-03 02:11:19
  • 关于Android实现简单的微信朋友圈分享功能

    2021-07-01 16:49:49
  • java后台接受到图片后保存方法

    2023-06-03 09:23:04
  • 简单了解Android性能优化方向及相关工具

    2022-10-15 19:10:54
  • 详解mybatis generator代码生成器的使用

    2021-08-28 09:05:42
  • Spring实战之Bean定义中的SpEL表达式语言支持操作示例

    2021-07-07 10:46:19
  • C#异步的世界(上)

    2021-09-21 06:01:43
  • Kotlin启动协程的三种方式示例详解

    2023-06-07 02:58:53
  • asp之家 软件编程 m.aspxhome.com