Java中FTPClient上傳中文目錄、中文檔案名稱亂碼問題解決方案_java

來源:互聯網
上載者:User

問題描述:

  使用org.apache.commons.net.ftp.FTPClient建立中文目錄、上傳中文檔案名稱時,目錄名及檔案名稱中的中文顯示為“??”。

原因:

  FTP協議裡面,規定檔案名稱編碼為iso-8859-1,所以目錄名或檔案名稱需要轉碼。

解決方案:

1.將中文的目錄或檔案名稱轉為iso-8859-1編碼的字元。參考代碼:

複製代碼 代碼如下:

   String name="目錄名或檔案名稱";

   name=new String(name.getBytes("GBK"),"iso-8859-1");// 轉換後的目錄名或檔案名稱。


2.設定linux環境變數
複製代碼 代碼如下:

export LC_ALL="zh_CN.GBK"
export LANG="zh_CN.GBK"

執行個體:
複製代碼 代碼如下:

    public boolean upLoadFile(File file, String path, String fileName) throws IOException {
        boolean result = false;
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(confService.getConfValue(PortalConfContants.FTP_CLIENT_HOST));
            ftpClient.login(confService.getConfValue(PortalConfContants.FTP_CLIENT_USERNAME), confService
                    .getConfValue(PortalConfContants.FTP_CLIENT_PASSWORD));
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

            // make directory
            if (path != null && !"".equals(path.trim())) {
                String[] pathes = path.split("/");
                for (String onepath : pathes) {
                    if (onepath == null || "".equals(onepath.trim())) {
                        continue;
                    }

                    onepath=new String(onepath.getBytes("GBK"),"iso-8859-1");                   
                    if (!ftpClient.changeWorkingDirectory(onepath)) {
                        ftpClient.makeDirectory(onepath);
                        ftpClient.changeWorkingDirectory(onepath);
                    }
                }
            }

            result = ftpClient.storeFile(new String(fileName.getBytes("GBK"),"iso-8859-1"), new FileInputStream(file));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ftpClient.logout();
        }
        return result;
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.