字符流读数据之一次读取一个字符
Reader类中的方法:<br /> int read() ;读一个字符,返回该字符对应的ASCIT码值,读不到返回-1.<br /> FileReader类的构造方法:<br /> public FileReader(String pathname);根据传入的字符串形式的路径,获取字符输入流对象
案例1
public class ReaderDemo {public static void main(String[] args) throws IOException {//需求:通过字符流读取数据,一次读取一个字符//1.创建字符输入流对象Reader reader = new FileReader("lib/1.txt");//2.读取数据/* int ch1 = reader.read();System.out.println(ch1);//97int ch2 = reader.read();System.out.println(ch2);//98int ch3 = reader.read();System.out.println(ch3);//99int ch4 = reader.read();System.out.println(ch4);//-1*//*优化上述的读法,用循环改进因为不知道循环次数,所以用while循环*///定义变量,用接收读取到的字符int ch1;while ((ch1 = reader.read()) != -1){//ch1 = reader.read();System.out.println(ch1);}//3.释放资源reader.close();}}
字符流读取数据之一次读取一个字符数组
_ _Reader类中的方法:
int read(char3 chs);一次读一个字符数组,将读取到的内容存入到数组中,并返回读取到的有效字符数,读不到返回-1.
FileReader类的构造方法:
public FileReader(String pathname);根据传入的字符串形式的路径,获取字符输入流对象
案例2
public class ReaderDemo1 {public static void main(String[] args) throws IOException {//通过字符流读取数据,一次读取一个字符数组//1.创建字符输入流对象Reader reader = new FileReader("lib/1.txt");//2.读取数据/* char chs[] = new char[3];int len1 = reader.read(chs);System.out.println(chs);//a,b,cSystem.out.println(len1);//3int len2 = reader.read(chs);System.out.println(chs);//d,e,fSystem.out.println(len2);//3int len3 = reader.read(chs);System.out.println(chs);//g,e,fSystem.out.println(len3);//1int len4 = reader.read(chs);System.out.println(chs);//g,e,fSystem.out.println(len4);//-1*///优化上述代码,while循环//定义字符数组char chs [] = new char[3];//定义一个变量,记录读取到的有效字符数int len;while ((len=reader.read(chs)) != -1){//将读取到的内容,转换成字符串String str = new String(chs,0,len);System.out.println(str);}//3.释放资源reader.close();}}
