java 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.     } 
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();
    }
}
這種方式沒啥可說的,比較簡單,也不存在中文亂碼的問題。貌似有個缺陷,不能操作大文件,有興趣的朋友可以試試。

第二種方式

  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.     } 
public class FtpApche {
    private static FTPClient ftpClient = new FTPClient();
    private static String encoding = System.getProperty("file.encoding");
    /**
     * Description: 向FTP服務器上傳文件
     * 
     * @Version1.0
     * @param url
     *            FTP服務器hostname
     * @param port
     *            FTP服務器端口
     * @param username
     *            FTP登錄賬號
     * @param password
     *            FTP登錄密碼
     * @param path
     *            FTP服務器保存目錄,如果是根目錄則爲“/”
     * @param filename
     *            上傳到FTP服務器上的文件名
     * @param input
     *            本地文件輸入流
     * @return 成功返回true,否則返回false
     */
    public static boolean uploadFile(String url, int port, String username,
            String password, String path, String filename, InputStream input) {
        boolean result = false;

        try {
            int reply;
            // 如果採用默認端口,可以使用ftp.connect(url)的方式直接連接FTP服務器
            ftpClient.connect(url);
            // ftp.connect(url, port);// 連接FTP服務器
            // 登錄
            ftpClient.login(username, password);
            ftpClient.setControlEncoding(encoding);
            // 檢驗是否連接成功
            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                System.out.println("連接失敗");
                ftpClient.disconnect();
                return result;
            }

            // 轉移工作目錄至指定目錄下
            boolean change = ftpClient.changeWorkingDirectory(path);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            if (change) {
                result = ftpClient.storeFile(new String(filename.getBytes(encoding),"iso-8859-1"), input);
                if (result) {
                    System.out.println("上傳成功!");
                }
            }
            input.close();
            ftpClient.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }

    /**
     * 將本地文件上傳到FTP服務器上
     * 
     */
    public void testUpLoadFromDisk() {
        try {
            FileInputStream in = new FileInputStream(new File("E:/號碼.txt"));
            boolean flag = uploadFile("127.0.0.1", 21, "zlb","123", "/", "哈哈.txt", in);
            System.out.println(flag);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }


    /**
     * Description: 從FTP服務器下載文件
     * 
     * @Version1.0
     * @param url
     *            FTP服務器hostname
     * @param port
     *            FTP服務器端口
     * @param username
     *            FTP登錄賬號
     * @param password
     *            FTP登錄密碼
     * @param remotePath
     *            FTP服務器上的相對路徑
     * @param fileName
     *            要下載的文件名
     * @param localPath
     *            下載後保存到本地的路徑
     * @return
     */
    public static boolean downFile(String url, int port, String username,
            String password, String remotePath, String fileName,
            String localPath) {
        boolean result = false;
        try {
            int reply;
            ftpClient.setControlEncoding(encoding);
            
            /*
             *  爲了上傳和下載中文文件,有些地方建議使用以下兩句代替
             *  new String(remotePath.getBytes(encoding),"iso-8859-1")轉碼。
             *  經過測試,通不過。
             */
//            FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
//            conf.setServerLanguageCode("zh");

            ftpClient.connect(url, port);
            // 如果採用默認端口,可以使用ftp.connect(url)的方式直接連接FTP服務器
            ftpClient.login(username, password);// 登錄
            // 設置文件傳輸類型爲二進制
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            // 獲取ftp登錄應答代碼
            reply = ftpClient.getReplyCode();
            // 驗證是否登陸成功
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                System.err.println("FTP server refused connection.");
                return result;
            }
            // 轉移到FTP服務器目錄至指定的目錄下
            ftpClient.changeWorkingDirectory(new String(remotePath.getBytes(encoding),"iso-8859-1"));
            // 獲取文件列表
            FTPFile[] fs = ftpClient.listFiles();
            for (FTPFile ff : fs) {
                if (ff.getName().equals(fileName)) {
                    File localFile = new File(localPath + "/" + ff.getName());
                    OutputStream is = new FileOutputStream(localFile);
                    ftpClient.retrieveFile(ff.getName(), is);
                    is.close();
                }
            }

            ftpClient.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }

    /**
     * 將FTP服務器上文件下載到本地
     * 
     */
    public void testDownFile() {
        try {
            boolean flag = downFile("127.0.0.1", 21, "zlb",
                    "123", "/", "哈哈.txt", "D:/");
            System.out.println(flag);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        FtpApche fa = new FtpApche();
        fa.testDownFile();
    }
}
這種方式的話需要注意中文亂碼問題啦,如果你設置不恰當,有可能上傳的文件名會爲亂碼,有的時候根本就上傳不上去,當然,也不會跟你提示,因爲原本就沒異常。在網上找了好多解答方案,衆說紛紜,幾乎都是從一個版本拷貝過去的,也沒有經過自己的真是檢驗。爲此,也吃了不少苦頭。大致分爲以下兩種解決方案:

1、加上以下三句即可解決

ftpClient.setControlEncoding(“GBK”);

FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
conf.setServerLanguageCode("zh");
解答:經過測試,根本上行不通,上述問題依然存在

2、與上述方式有所類似,但我覺得這種方式更靠譜一點

首先,加上ftpClient.setControlEncoding(“GBK”);這一句,然後,將所有的中文進行轉碼爲“ISO-8859-1”格式,如下:

ftpClient.changeWorkingDirectory(new String(remotePath.getBytes("GBK"),"iso-8859-1"));

解答:經過測試,仍然行不通,之所以我說此方式更靠譜一點,請繼續往下看

首先我們來說說爲什麼要進行轉碼:

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

以上代碼均通過自己測試,望能爲大家解決一下問題!順便提供一下FTP服務器搭建工具Serv-U,裏面包含了註冊機,需要的請點擊下載。如果註冊時有什麼問題請及時回覆!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章