寫檔案為什麼出現中文亂碼

來源:互聯網
上載者:User
我無意看到
DataOutputStream

的源碼.結果發現這段.

    /**     * Writes out the string to the underlying output stream as a      * sequence of bytes. Each character in the string is written out, in      * sequence, by discarding its high eight bits. If no exception is      * thrown, the counter written is incremented by the      * length of s.     *     * @param      s   a string of bytes to be written.     * @exception  IOException  if an I/O error occurs.     * @see        java.io.FilterOutputStream#out     */    public final void writeBytes(String s) throws IOException {int len = s.length();for (int i = 0 ; i out.writer((byte)s.charAt(i));//這個因為英文一個位元組就夠了,可中文是兩個位元組,結果我們的中文就在這裡被扔掉一半.於是就再輸出就亂碼了.相比之下:
 /**     * Writes a string to the underlying output stream as a sequence of      * characters. Each character is written to the data output stream as      * if by the writeChar method. If no exception is      * thrown, the counter written is incremented by twice      * the length of s.     *     * @param      s   a String value to be written.     * @exception  IOException  if an I/O error occurs.     * @see        java.io.DataOutputStream#writeChar(int)     * @see        java.io.FilterOutputStream#out     */    public final void writeChars(String s) throws IOException {        int len = s.length();        for (int i = 0 ; i >> 8) & 0xFF);             out.write((v >>> 0) & 0xFF);         }        incCount(len * 2);    }

這個要好一點了,中文就可以真確的被寫入了.

聯繫我們

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