溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java IO流 文件的編碼實例代碼

發(fā)布時間:2020-09-27 04:43:02 來源:腳本之家 閱讀:104 作者:tianxintian22 欄目:編程語言

•文件的編碼

package cn.test;
import java.io.UnsupportedEncodingException;
public class Demo15 {
  public static void main(String[] args) throws UnsupportedEncodingException {
    String str = "你好ABC123";
    byte[] b1 = str.getBytes();//轉(zhuǎn)換成字節(jié)系列用的是項目默認的編碼
    for (byte b : b1) {
      //把字節(jié)(轉(zhuǎn)換成了int)以十六進制方式顯示
      System.out.print(Integer.toHexString(b & 0xff) + " ");
    }
    System.out.println("");
    //utf8編碼,中文占用3個字節(jié),英文和數(shù)字占用1個字節(jié)
    byte[] b2 = str.getBytes("utf8");
    for (byte b : b2) {
      System.out.print(Integer.toHexString(b & 0xff) + " ");
    }
    System.out.println("");
    //gbk編碼,中文占用兩個字節(jié),英文和數(shù)字占用1個字節(jié)
    byte[] b3 = str.getBytes("gbk");
    for (byte b : b3) {
      System.out.print(Integer.toHexString(b & 0xff) + " ");
    }
    System.out.println("");
    //java是雙字節(jié)編碼 utf-16be
    //utf-16be編碼,中文占2個字節(jié),英文和數(shù)字也占用2個字節(jié)
    byte[] b4 = str.getBytes("utf-16be");
    for (byte b : b4) {
      System.out.print(Integer.toHexString(b & 0xff) + " ");
    }
    System.out.println("");
    //當字節(jié)序列是某種編碼時,這時候想把字節(jié)序列變成字符串,也需要用這種編碼方式,否則會出現(xiàn)亂碼
    String str1 = new String(b4);//使用項目默認的編碼
    System.out.println(str1);
    String str2 = new String(b4, "utf-16be");
    System.out.println(str2);
  }
}

  執(zhí)行結果:

e4 bd a0 e5 a5 bd 41 42 43 31 32 33 
e4 bd a0 e5 a5 bd 41 42 43 31 32 33 
c4 e3 ba c3 41 42 43 31 32 33 
4f 60 59 7d 0 41 0 42 0 43 0 31 0 32 0 33 
O`Y}ABC123
你好ABC123

  文件就是字節(jié)序列,可以是任意編碼的字節(jié)序列。

  如果我們在中文機器上直接創(chuàng)建文本文件,那么該文本文件只認識ansi編碼(中文系統(tǒng)下,ansi編碼代表gbk編碼)

好了,以上所述是小編給大家介紹的Java IO流 文件的編碼的實例代碼,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI