• FTP文件上传与下载


    实现FTP文件上传与下载可以通过以下两种种方式实现,分别为:1、通过JDK自带的API实现;2、通过Apache提供的API是实现。

    第一种方式

    1. package com.cloudpower.util;  
    2.   
    3. import java.io.File;  
    4. import java.io.FileInputStream;  
    5. import java.io.FileOutputStream;  
    6. import java.io.IOException;  
    7.   
    8. import sun.net.TelnetInputStream;  
    9. import sun.net.TelnetOutputStream;  
    10. import sun.net.ftp.FtpClient;  
    11.   
    12. /** 
    13.  * Java自带的API对FTP的操作 
    14.  * @Title:Ftp.java 
    15.  * @author: 周玲斌   
    16.  */  
    17. public class Ftp {  
    18.     /** 
    19.      * 本地文件名 
    20.      */  
    21.     private String localfilename;  
    22.     /** 
    23.      * 远程文件名 
    24.      */  
    25.     private String remotefilename;  
    26.     /** 
    27.      * FTP客户端 
    28.      */  
    29.     private FtpClient ftpClient;  
    30.   
    31.     /** 
    32.      * 服务器连接 
    33.      * @param ip 服务器IP 
    34.      * @param port 服务器端口 
    35.      * @param user 用户名 
    36.      * @param password 密码 
    37.      * @param path 服务器路径 
    38.      * @author 周玲斌 
    39.      * @date   2012-7-11 
    40.      */  
    41.     public void connectServer(String ip, int port, String user,  
    42.             String password, String path) {  
    43.         try {  
    44.             /* ******连接服务器的两种方法*******/  
    45.             //第一种方法  
    46. //            ftpClient = new FtpClient();  
    47. //            ftpClient.openServer(ip, port);  
    48.             //第二种方法  
    49.             ftpClient = new FtpClient(ip);  
    50.               
    51.             ftpClient.login(user, password);  
    52.             // 设置成2进制传输  
    53.             ftpClient.binary();  
    54.             System.out.println("login success!");  
    55.             if (path.length() != 0){  
    56.                 //把远程系统上的目录切换到参数path所指定的目录  
    57.                 ftpClient.cd(path);  
    58.             }  
    59.             ftpClient.binary();  
    60.         } catch (IOException ex) {  
    61.             ex.printStackTrace();  
    62.             throw new RuntimeException(ex);  
    63.         }  
    64.     }  
    65.     /** 
    66.      * 关闭连接 
    67.      * @author 周玲斌 
    68.      * @date   2012-7-11 
    69.      */  
    70.     public void closeConnect() {  
    71.         try {  
    72.             ftpClient.closeServer();  
    73.             System.out.println("disconnect success");  
    74.         } catch (IOException ex) {  
    75.             System.out.println("not disconnect");  
    76.             ex.printStackTrace();  
    77.             throw new RuntimeException(ex);  
    78.         }  
    79.     }  
    80.     /** 
    81.      * 上传文件 
    82.      * @param localFile 本地文件 
    83.      * @param remoteFile 远程文件 
    84.      * @author 周玲斌 
    85.      * @date   2012-7-11 
    86.      */  
    87.     public void upload(String localFile, String remoteFile) {  
    88.         this.localfilename = localFile;  
    89.         this.remotefilename = remoteFile;  
    90.         TelnetOutputStream os = null;  
    91.         FileInputStream is = null;  
    92.         try {  
    93.             //将远程文件加入输出流中  
    94.             os = ftpClient.put(this.remotefilename);  
    95.             //获取本地文件的输入流  
    96.             File file_in = new File(this.localfilename);  
    97.             is = new FileInputStream(file_in);  
    98.             //创建一个缓冲区  
    99.             byte[] bytes = new byte[1024];  
    100.             int c;  
    101.             while ((c = is.read(bytes)) != -1) {  
    102.                 os.write(bytes, 0, c);  
    103.             }  
    104.             System.out.println("upload success");  
    105.         } catch (IOException ex) {  
    106.             System.out.println("not upload");  
    107.             ex.printStackTrace();  
    108.             throw new RuntimeException(ex);  
    109.         } finally{  
    110.             try {  
    111.                 if(is != null){  
    112.                     is.close();  
    113.                 }  
    114.             } catch (IOException e) {  
    115.                 e.printStackTrace();  
    116.             } finally {  
    117.                 try {  
    118.                     if(os != null){  
    119.                         os.close();  
    120.                     }  
    121.                 } catch (IOException e) {  
    122.                     e.printStackTrace();  
    123.                 }  
    124.             }  
    125.         }  
    126.     }  
    127.       
    128.     /** 
    129.      * 下载文件 
    130.      * @param remoteFile 远程文件路径(服务器端) 
    131.      * @param localFile 本地文件路径(客户端) 
    132.      * @author 周玲斌 
    133.      * @date   2012-7-11 
    134.      */  
    135.     public void download(String remoteFile, String localFile) {  
    136.         TelnetInputStream is = null;  
    137.         FileOutputStream os = null;  
    138.         try {  
    139.             //获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。  
    140.             is = ftpClient.get(remoteFile);  
    141.             File file_in = new File(localFile);  
    142.             os = new FileOutputStream(file_in);  
    143.             byte[] bytes = new byte[1024];  
    144.             int c;  
    145.             while ((c = is.read(bytes)) != -1) {  
    146.                 os.write(bytes, 0, c);  
    147.             }  
    148.             System.out.println("download success");  
    149.         } catch (IOException ex) {  
    150.             System.out.println("not download");  
    151.             ex.printStackTrace();  
    152.             throw new RuntimeException(ex);  
    153.         } finally{  
    154.             try {  
    155.                 if(is != null){  
    156.                     is.close();  
    157.                 }  
    158.             } catch (IOException e) {  
    159.                 e.printStackTrace();  
    160.             } finally {  
    161.                 try {  
    162.                     if(os != null){  
    163.                         os.close();  
    164.                     }  
    165.                 } catch (IOException e) {  
    166.                     e.printStackTrace();  
    167.                 }  
    168.             }  
    169.         }  
    170.     }  
    171.   
    172.     public static void main(String agrs[]) {  
    173.   
    174.         String filepath[] = { "/temp/aa.txt", "/temp/regist.log"};  
    175.         String localfilepath[] = { "C:\tmp\1.txt","C:\tmp\2.log"};  
    176.   
    177.         Ftp fu = new Ftp();  
    178.         /* 
    179.          * 使用默认的端口号、用户名、密码以及根目录连接FTP服务器 
    180.          */  
    181.         fu.connectServer("127.0.0.1", 22, "anonymous", "IEUser@", "/temp");  
    182.           
    183.         //下载  
    184.         for (int i = 0; i < filepath.length; i++) {  
    185.             fu.download(filepath[i], localfilepath[i]);  
    186.         }  
    187.           
    188.         String localfile = "E:\号码.txt";  
    189.         String remotefile = "/temp/哈哈.txt";  
    190.         //上传  
    191.         fu.upload(localfile, remotefile);  
    192.         fu.closeConnect();  
    193.     }  
    194. }  

    这种方式没啥可说的,比较简单,也不存在中文乱码的问题。貌似有个缺陷,不能操作大文件,有兴趣的朋友可以试试。

    第二种方式

    1. public class FtpApche {  
    2.     private static FTPClient ftpClient = new FTPClient();  
    3.     private static String encoding = System.getProperty("file.encoding");  
    4.     /** 
    5.      * Description: 向FTP服务器上传文件 
    6.      *  
    7.      * @Version1.0 
    8.      * @param url 
    9.      *            FTP服务器hostname 
    10.      * @param port 
    11.      *            FTP服务器端口 
    12.      * @param username 
    13.      *            FTP登录账号 
    14.      * @param password 
    15.      *            FTP登录密码 
    16.      * @param path 
    17.      *            FTP服务器保存目录,如果是根目录则为“/” 
    18.      * @param filename 
    19.      *            上传到FTP服务器上的文件名 
    20.      * @param input 
    21.      *            本地文件输入流 
    22.      * @return 成功返回true,否则返回false 
    23.      */  
    24.     public static boolean uploadFile(String url, int port, String username,  
    25.             String password, String path, String filename, InputStream input) {  
    26.         boolean result = false;  
    27.   
    28.         try {  
    29.             int reply;  
    30.             // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器  
    31.             ftpClient.connect(url);  
    32.             // ftp.connect(url, port);// 连接FTP服务器  
    33.             // 登录  
    34.             ftpClient.login(username, password);  
    35.             ftpClient.setControlEncoding(encoding);  
    36.             // 检验是否连接成功  
    37.             reply = ftpClient.getReplyCode();  
    38.             if (!FTPReply.isPositiveCompletion(reply)) {  
    39.                 System.out.println("连接失败");  
    40.                 ftpClient.disconnect();  
    41.                 return result;  
    42.             }  
    43.   
    44.             // 转移工作目录至指定目录下  
    45.             boolean change = ftpClient.changeWorkingDirectory(path);  
    46.             ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
    47.             if (change) {  
    48.                 result = ftpClient.storeFile(new String(filename.getBytes(encoding),"iso-8859-1"), input);  
    49.                 if (result) {  
    50.                     System.out.println("上传成功!");  
    51.                 }  
    52.             }  
    53.             input.close();  
    54.             ftpClient.logout();  
    55.         } catch (IOException e) {  
    56.             e.printStackTrace();  
    57.         } finally {  
    58.             if (ftpClient.isConnected()) {  
    59.                 try {  
    60.                     ftpClient.disconnect();  
    61.                 } catch (IOException ioe) {  
    62.                 }  
    63.             }  
    64.         }  
    65.         return result;  
    66.     }  
    67.   
    68.     /** 
    69.      * 将本地文件上传到FTP服务器上 
    70.      *  
    71.      */  
    72.     public void testUpLoadFromDisk() {  
    73.         try {  
    74.             FileInputStream in = new FileInputStream(new File("E:/号码.txt"));  
    75.             boolean flag = uploadFile("127.0.0.1", 21, "zlb","123", "/", "哈哈.txt", in);  
    76.             System.out.println(flag);  
    77.         } catch (FileNotFoundException e) {  
    78.             e.printStackTrace();  
    79.         }  
    80.     }  
    81.   
    82.   
    83.     /** 
    84.      * Description: 从FTP服务器下载文件 
    85.      *  
    86.      * @Version1.0 
    87.      * @param url 
    88.      *            FTP服务器hostname 
    89.      * @param port 
    90.      *            FTP服务器端口 
    91.      * @param username 
    92.      *            FTP登录账号 
    93.      * @param password 
    94.      *            FTP登录密码 
    95.      * @param remotePath 
    96.      *            FTP服务器上的相对路径 
    97.      * @param fileName 
    98.      *            要下载的文件名 
    99.      * @param localPath 
    100.      *            下载后保存到本地的路径 
    101.      * @return 
    102.      */  
    103.     public static boolean downFile(String url, int port, String username,  
    104.             String password, String remotePath, String fileName,  
    105.             String localPath) {  
    106.         boolean result = false;  
    107.         try {  
    108.             int reply;  
    109.             ftpClient.setControlEncoding(encoding);  
    110.               
    111.             /* 
    112.              *  为了上传和下载中文文件,有些地方建议使用以下两句代替 
    113.              *  new String(remotePath.getBytes(encoding),"iso-8859-1")转码。 
    114.              *  经过测试,通不过。 
    115.              */  
    116. //            FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);  
    117. //            conf.setServerLanguageCode("zh");  
    118.   
    119.             ftpClient.connect(url, port);  
    120.             // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器  
    121.             ftpClient.login(username, password);// 登录  
    122.             // 设置文件传输类型为二进制  
    123.             ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);  
    124.             // 获取ftp登录应答代码  
    125.             reply = ftpClient.getReplyCode();  
    126.             // 验证是否登陆成功  
    127.             if (!FTPReply.isPositiveCompletion(reply)) {  
    128.                 ftpClient.disconnect();  
    129.                 System.err.println("FTP server refused connection.");  
    130.                 return result;  
    131.             }  
    132.             // 转移到FTP服务器目录至指定的目录下  
    133.             ftpClient.changeWorkingDirectory(new String(remotePath.getBytes(encoding),"iso-8859-1"));  
    134.             // 获取文件列表  
    135.             FTPFile[] fs = ftpClient.listFiles();  
    136.             for (FTPFile ff : fs) {  
    137.                 if (ff.getName().equals(fileName)) {  
    138.                     File localFile = new File(localPath + "/" + ff.getName());  
    139.                     OutputStream is = new FileOutputStream(localFile);  
    140.                     ftpClient.retrieveFile(ff.getName(), is);  
    141.                     is.close();  
    142.                 }  
    143.             }  
    144.   
    145.             ftpClient.logout();  
    146.             result = true;  
    147.         } catch (IOException e) {  
    148.             e.printStackTrace();  
    149.         } finally {  
    150.             if (ftpClient.isConnected()) {  
    151.                 try {  
    152.                     ftpClient.disconnect();  
    153.                 } catch (IOException ioe) {  
    154.                 }  
    155.             }  
    156.         }  
    157.         return result;  
    158.     }  
    159.   
    160.     /** 
    161.      * 将FTP服务器上文件下载到本地 
    162.      *  
    163.      */  
    164.     public void testDownFile() {  
    165.         try {  
    166.             boolean flag = downFile("127.0.0.1", 21, "zlb",  
    167.                     "123", "/", "哈哈.txt", "D:/");  
    168.             System.out.println(flag);  
    169.         } catch (Exception e) {  
    170.             e.printStackTrace();  
    171.         }  
    172.     }  
    173.       
    174.     public static void main(String[] args) {  
    175.         FtpApche fa = new FtpApche();  
    176.         fa.testDownFile();  
    177.     }  
    178. }  

    这 种方式的话需要注意中文乱码问题啦,如果你设置不恰当,有可能上传的文件名会为乱码,有的时候根本就上传不上去,当然,也不会跟你提示,因为原本就没异常。

    首先我们来说说为什么要进行转码:

    因为在FTP协议里面,规定文件名编码为iso-8859-1,所以目录名或文件名需要转码。

    接下来的问题是,我们应该将什么编码转换为此格式。因此,就有了第二种解决方案——把 GBK格式的转换为ISO-8859-1格式。而且,有的人还说,必须得这么转。其实,之所以他们能这么说,我觉得完全是巧合。它的真正原理是,既然FTP协议规定的编码格式是“ISO-8859-1”,那么我们确实得将格式转换一下,然后等服务器收到文件时再自动转换为系统自带的编码格式,因此,关键不是规定为什么格式,而是取决于FTP服务器的编码格式。因此,如果FTP系统的编码格式为“GBK”时,第二种方式肯定会成功;但是,如果系统的编码格式为“UTF-8”时,那就会仍然出现乱码啦。所以,我们只能通过代码先获取系统的编码格式,然后通过此编码格式转换为ISO-8859-1的编码格 式。获取方式如下:

    private static String encoding = System.getProperty("file.encoding");

  • 相关阅读:
    Tomcat服务器本地的搭建,以及在 IDEA软件下的配置,以及项目的测试运行(基于supermvc框架下的web)
    数据可视化-EChart2.0.0使用中遇到的2个问题
    数据可视化-EChart2.0使用总结2
    数据可视化-EChart2.0使用总结1
    Mac下有道笔记本问题反馈
    修复bootstrap daterangepicker中的3个问题
    使用jQuery封装实用函数
    Web Fundamentsals学习1-Multiple-Screen-Site
    安装Git
    学会使用Git创建分支
  • 原文地址:https://www.cnblogs.com/qingyuuu/p/4561874.html
Copyright © 2020-2023  润新知