字符流读数据的两种方式
字符流读数据的两种方式
-
构造方法:
InputStreamReader(InputStream in): 创建一个使用默认字符集 -
读数据的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(); }}
输出的内容