> 文档中心 > 字符流读数据的两种方式

字符流读数据的两种方式


字符读数据的两种方式

  1. 构造方法:
    InputStreamReader(InputStream in): 创建一个使用默认字符集

  2. 读数据的2种方式:
    int read(); 一次读取一个字符
    int read(char[] cbu f); 一次读取一个字符数组数据

以图文和代码内容形式讲解

图文:
柏维怡我爱你
int read(); 一次读取一个字符:

package Demo;import java.io.*;public class Demo {    public static void main(String[] args) throws IOException {  //创建字符输入流 InputStreamReader ir = new InputStreamReader(new FileInputStream("D:\\item\\Hellow\\src\\java.txt")); //读取字符 //int read(); 一次读取一个字符 int s; while ((s = ir.read())!=-1){     System.out.print((char)s); } //释放资源 ir.close();    }}

int read(char[] cbu f); 一次读取一个字符数组数据:

package Demo;import java.io.*;public class Demo {    public static void main(String[] args) throws IOException {  //创建字符输入流 InputStreamReader ir = new InputStreamReader(new FileInputStream("D:\\item\\Hellow\\src\\java.txt")); //读取字符 //int read(char[] cbu f); 一次读取一个字符数组数据 int len; char[] chars = new char[1024]; while ((len = ir.read(chars))!=-1){     System.out.print(new String(chars,0,len)); } //释放资源 ir.close();    }}

输出的内容
字符流读数据的两种方式