關於 Java 的系統屬性 sun.jnu.encoding 和 file.encoding 的區別

來源:互聯網
上載者:User

關於 Java 的系統屬性 sun.jnu.encoding 和 file.encoding 的區別

        sun.jnu.encoding 影響檔案名稱的建立,而 file.encoding 則影響到檔案內容。

        所以說,在我們使用 Java 處理中文檔案的時候,如果發現檔案的中文內容沒有亂碼,而檔案的中文名發生亂碼,我們就應當多考慮一下 sun.jnu.encoding 和 file.encoding 的區別了。

        支援中文檔案目錄的 org.apache.tools.zip.* 打包解壓縮中文檔案夾都沒有問題的。但有的時候打包後的中文檔案名稱會出現亂碼,這是為什麼呢?查看 org.apache.tools.zip.ZipOutputStream 的 API 會發現關於其 getEncoding()  方法的說明:“The encoding to use for filenames and the file comment.”,將以下語句執行一下:

org.apache.tools.zip.ZipOutputStream out = new org.apache.tools.zip.ZipOutputStream(new java.io.FileOutputStream("D:/temp/testfile.zip"));System.out.println("out.getEncoding()=" + out.getEncoding());

        執行結果如下:

out.getEncoding()=null

        問題就在這裡了。在 org.apache.tools.zip.ZipOutputStream 建立好以後,手工設定一下:

out.setEncoding(System.getProperty("sun.jnu.encoding"));

        發現打包後中文名可以正常顯示了。

參考一:http://stackoverflow.com/questions/1066845/what-exactly-is-sun-jnu-encoding【stackoverflow 關於 sun.jnu.encoding 的解答】,

參考二:http://www.jajakarta.org/ant/ant-1.6.1/docs/ja/manual/api/org/apache/tools/zip/ZipOutputStream.html【ZipOutputStream 的 API】,

參考三:http://massapi.com/source/apache-ant-1.8.2/src/main/org/apache/tools/zip/ZipOutputStream.java.html【ZipOutputStream 的原始碼】。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.