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
投稿

猜你喜欢

  • windows下java环境变量的设置方法

    2022-12-01 03:13:14
  • Java如何基于ProcessBuilder类调用外部程序

    2023-11-27 20:19:57
  • nacos使用占位符${}进行参数配置的方法

    2022-07-15 08:59:07
  • feign实现传递参数的三种方式小结

    2021-06-18 00:09:53
  • Java实现五子棋游戏

    2022-07-08 12:50:27
  • Java编程将汉字转Unicode码代码示例

    2023-11-09 17:33:39
  • Android之使用Bundle进行IPC详解

    2023-09-27 22:44:56
  • springcloud之自定义简易消费服务组件

    2022-01-29 00:18:24
  • Java面试必备八股文整理

    2023-11-29 12:03:50
  • mybatis中foreach嵌套if标签方式

    2023-11-20 23:11:05
  • Spring实战之ResourceLoader接口资源加载用法示例

    2023-11-20 12:16:49
  • kafka并发写大消息异常TimeoutException排查记录

    2023-11-27 23:07:11
  • SpringBoot创建maven多模块项目实战代码

    2023-11-11 04:05:32
  • spring boot集成smart-doc自动生成接口文档详解

    2023-11-28 23:08:02
  • c#处理3种json数据的实例

    2023-06-23 19:12:47
  • Hibernate实现批量添加数据的方法

    2023-11-29 08:53:56
  • Java KindEditor粘贴图片自动上传到服务器功能实现

    2023-08-07 01:42:33
  • Windows下Java环境配置的超详细教程

    2021-12-18 19:19:16
  • Springcloud微服务架构基础知识解析

    2023-01-26 14:37:10
  • 详解Java设计模式编程中的访问者模式

    2023-11-28 01:00:43
  • asp之家 软件编程 m.aspxhome.com