实现FTP文件上传与下载可以通过以下两种种方式实现(不知道还有没有其他方式),分别为:1、通过JDK自带的API实现;2、通过Apache提供的API是实现。


JDK:

package com.cloudpower.util;
import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;import sun.net.TelnetInputStream;
 import sun.net.TelnetOutputStream;
 import sun.net.ftp.FtpClient;/**
  * Java自带的API对FTP的操作
  * @Title:Ftp.java
  * @author: 周玲斌  
  */
 public class Ftp {
     /**
      * 本地文件名
      */
     private String localfilename;
     /**
      * 远程文件名
      */
     private String remotefilename;
     /**
      * FTP客户端
      */
     private FtpClient ftpClient;    /**
      * 服务器连接
      * @param ip 服务器IP
      * @param port 服务器端口
      * @param user 用户名
      * @param password 密码
      * @param path 服务器路径
      * @author 周玲斌
      * @date   2012-7-11
      */
     public void connectServer(String ip, int port, String user,
             String password, String path) {
         try {
             /* ******连接服务器的两种方法*******/
             //第一种方法
 //            ftpClient = new FtpClient();
 //            ftpClient.openServer(ip, port);
             //第二种方法
             ftpClient = new FtpClient(ip);
             
             ftpClient.login(user, password);
             // 设置成2进制传输
             ftpClient.binary();
             System.out.println("login success!");
             if (path.length() != 0){
                 //把远程系统上的目录切换到参数path所指定的目录
                 ftpClient.cd(path);
             }
             ftpClient.binary();
         } catch (IOException ex) {
             ex.printStackTrace();
             throw new RuntimeException(ex);
         }
     }
     /**
      * 关闭连接
      * @author 周玲斌
      * @date   2012-7-11
      */
     public void closeConnect() {
         try {
             ftpClient.closeServer();
             System.out.println("disconnect success");
         } catch (IOException ex) {
             System.out.println("not disconnect");
             ex.printStackTrace();
             throw new RuntimeException(ex);
         }
     }
     /**
      * 上传文件
      * @param localFile 本地文件
      * @param remoteFile 远程文件
      * @author 周玲斌
      * @date   2012-7-11
      */
     public void upload(String localFile, String remoteFile) {
         this.localfilename = localFile;
         this.remotefilename = remoteFile;
         TelnetOutputStream os = null;
         FileInputStream is = null;
         try {
             //将远程文件加入输出流中
             os = ftpClient.put(this.remotefilename);
             //获取本地文件的输入流
             File file_in = new File(this.localfilename);
             is = new FileInputStream(file_in);
             //创建一个缓冲区
             byte[] bytes = new byte[1024];
             int c;
             while ((c = is.read(bytes)) != -1) {
                 os.write(bytes, 0, c);
             }
             System.out.println("upload success");
         } catch (IOException ex) {
             System.out.println("not upload");
             ex.printStackTrace();
             throw new RuntimeException(ex);
         } finally{
             try {
                 if(is != null){
                     is.close();
                 }
             } catch (IOException e) {
                 e.printStackTrace();
             } finally {
                 try {
                     if(os != null){
                         os.close();
                     }
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
         }
     }
     
     /**
      * 下载文件
      * @param remoteFile 远程文件路径(服务器端)
      * @param localFile 本地文件路径(客户端)
      * @author 周玲斌
      * @date   2012-7-11
      */
     public void download(String remoteFile, String localFile) {
         TelnetInputStream is = null;
         FileOutputStream os = null;
         try {
             //获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。
             is = ftpClient.get(remoteFile);
             File file_in = new File(localFile);
             os = new FileOutputStream(file_in);
             byte[] bytes = new byte[1024];
             int c;
             while ((c = is.read(bytes)) != -1) {
                 os.write(bytes, 0, c);
             }
             System.out.println("download success");
         } catch (IOException ex) {
             System.out.println("not download");
             ex.printStackTrace();
             throw new RuntimeException(ex);
         } finally{
             try {
                 if(is != null){
                     is.close();
                 }
             } catch (IOException e) {
                 e.printStackTrace();
             } finally {
                 try {
                     if(os != null){
                         os.close();
                     }
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
         }
     }    public static void main(String agrs[]) {
        String filepath[] = { "/temp/aa.txt", "/temp/regist.log"};
         String localfilepath[] = { "C:\\tmp\\1.txt","C:\\tmp\\2.log"};        Ftp fu = new Ftp();
         /*
          * 使用默认的端口号、用户名、密码以及根目录连接FTP服务器
          */
         fu.connectServer("127.0.0.1", 22, "anonymous", "IEUser@", "/temp");
         
         //下载
         for (int i = 0; i < filepath.length; i++) {
             fu.download(filepath[i], localfilepath[i]);
         }
         
         String localfile = "E:\\号码.txt";
         String remotefile = "/temp/哈哈.txt";
         //上传
         fu.upload(localfile, remotefile);
         fu.closeConnect();
     }
 }

另外,http://www.codefans.net/articles/839.shtml 中对sendServer()描述的比较详细。

Apache: 

import java.io.File;  
     import java.io.FileInputStream;  
     import org.apache.commons.net.ftp.FTPClient;  
     import org.apache.commons.net.ftp.FTPReply;  
       
     public class test {    
          
         private  FTPClient ftp;    
         /** 
          *  
          * @param path 上传到ftp服务器哪个路径下    
          * @param addr 地址 
          * @param port 端口号 
          * @param username 用户名 
          * @param password 密码 
          * @return 
          * @throws Exception 
          */  
         private  boolean connect(String path,String addr,int port,String username,String password) throws Exception {   
             boolean result = false;    
             ftp = new FTPClient();    
             int reply;    
             ftp.connect(addr,port);   
             ftp.login(username,password);   
             ftp.setFileType(FTPClient.BINARY_FILE_TYPE);   
             reply = ftp.getReplyCode();   
             if (!FTPReply.isPositiveCompletion(reply)) {    
                 ftp.disconnect();   
                 return result;    
             }    
             ftp.changeWorkingDirectory(path);   
             result = true;    
             return result;    
         }    
         /** 
          *  
          * @param file 上传的文件或文件夹 
          * @throws Exception 
          */  
         private void upload(File file) throws Exception{    
             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);    
                         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());    
                 FileInputStream input = new FileInputStream(file2);    
                 ftp.storeFile(file2.getName(), input);   
                 input.close();      
             }    
         }    
        public static void main(String[] args) throws Exception{  
           test t = new test();  
           t.connect("", "localhost", 21, "yhh", "yhhazr");  
           File file = new File("e:\\uploadify");  
           t.upload(file);  
        }  
     }

 

因为在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");