InputStreamReader介绍代码实现
生活随笔
收集整理的這篇文章主要介紹了
InputStreamReader介绍代码实现
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
package com.learn.demo03.ReverseStream;import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;/*java.io.InputStreamReader extends ReaderInputStreamReader:是字節(jié)流通向字符流的橋梁:它使用指定的 charset 讀取字節(jié)并將其解碼為字符。(解碼:把看不懂的變成能看懂的)繼承自父類的共性成員方法:int read() 讀取單個字符并返回。int read(char[] cbuf)一次讀取多個字符,將字符讀入數(shù)組。void close() 關(guān)閉該流并釋放與之關(guān)聯(lián)的所有資源。構(gòu)造方法:InputStreamReader(InputStream in) 創(chuàng)建一個使用默認字符集的 InputStreamReader。InputStreamReader(InputStream in, String charsetName) 創(chuàng)建使用指定字符集的 InputStreamReader。參數(shù):InputStream in:字節(jié)輸入流,用來讀取文件中保存的字節(jié)String charsetName:指定的編碼表名稱,不區(qū)分大小寫,可以是utf-8/UTF-8,gbk/GBK,...不指定默認使用UTF-8使用步驟:1.創(chuàng)建InputStreamReader對象,構(gòu)造方法中傳遞字節(jié)輸入流和指定的編碼表名稱2.使用InputStreamReader對象中的方法read讀取文件3.釋放資源注意事項:構(gòu)造方法中指定的編碼表名稱要和文件的編碼相同,否則會發(fā)生亂碼*/
public class Demo03InputStreamReader {public static void main(String[] args) throws IOException {//read_utf_8();read_gbk();}/*使用InputStreamReader讀取GBK格式的文件*/private static void read_gbk() throws IOException {//1.創(chuàng)建InputStreamReader對象,構(gòu)造方法中傳遞字節(jié)輸入流和指定的編碼表名稱//InputStreamReader isr = new InputStreamReader(new FileInputStream("10_IO\\gbk.txt"),"UTF-8");//???InputStreamReader isr = new InputStreamReader(new FileInputStream("gbk.txt"),"GBK");//你好//2.使用InputStreamReader對象中的方法read讀取文件int len = 0;while((len = isr.read())!=-1){System.out.println((char)len);}//3.釋放資源isr.close();}/*使用InputStreamReader讀取UTF-8格式的文件*/private static void read_utf_8() throws IOException {//1.創(chuàng)建InputStreamReader對象,構(gòu)造方法中傳遞字節(jié)輸入流和指定的編碼表名稱//InputStreamReader isr = new InputStreamReader(new FileInputStream("10_IO\\utf_8.txt"),"UTF-8");InputStreamReader isr = new InputStreamReader(new FileInputStream("utf_8.txt"));//不指定默認使用UTF-8//2.使用InputStreamReader對象中的方法read讀取文件int len = 0;while((len = isr.read())!=-1){System.out.println((char)len);}//3.釋放資源isr.close();}
}
?
總結(jié)
以上是生活随笔為你收集整理的InputStreamReader介绍代码实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OutputStreamWriter介绍
- 下一篇: 转换文件编码