歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java中以指定編碼方式讀取字符流

Java中以指定編碼方式讀取字符流

日期:2017/3/1 10:20:08   编辑:Linux編程

Java中可以以指定的編碼方式讀取字符流,比如utf-8,utf-16,utf-32和gbk等,也可以自己制定解碼算法。

這裡涉及的一個class就是InputStreamReader,它用於在字節流上建立字符流。

構造方式有:

public InputStreamReader(InputStream in)

public InputStreamReader(InputStream in,String enc)

public InputStreamReader(InputStream in,CharsetDecoder dec)

public InputStreamReader(InputStream in,Charset charset)

例如可以利用以下代碼建立一個以gbk格式讀取一個文件的BufferedReader br

  1. File f=new File("/home/tobacco/Downloads/MESSAGE.txt");
  2. try {
  3. try {
  4. BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(f),"gbk"));
} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}
Copyright © Linux教程網 All Rights Reserved