Java——字符流读取数据——按照单个字符读取
创建字符流度文件对象:
Reader reader = new FileReader("readme.txt")
调用读取方法读取对象:
int data =reader.read()
读取一个字符,返回该字符代表的整数,若到达流的末尾,返回-1
异常处理:
throws IOException
关闭资源
reader.close()
import java.io.Reader; import java.io.FileReader; import java.io.*; public class test { public static void main(String[] args) throws IOException { //通过字符流读取数据 //1.创建字符输入流对象 Reader reader = new FileReader("C:\\Users\\15773\\Desktop\\test\\file2.txt"); // 2.读取数据 int ch1 = reader.read(); System.out.println(ch1); int ch2 = reader.read(); System.out.println(ch2); System.out.println("----------------------"); //使用while 循环 int ch;//用来接收读取的字符 while ((ch = reader.read()) !=-1){ System.out.println(ch); } // 3释放资源 reader.close(); } }
import java.io.Reader; import java.io.FileReader; import java.io.*; public class test { public static void main(String[] args) throws IOException { //通过字符流读取数据 //1.创建字符输入流对象 Reader reader = new FileReader("C:\\Users\\15773\\Desktop\\test\\file2.txt"); char[] chs = new char[3]; int len1 = reader.read(chs); System.out.println(chs); System.out.println(len1); System.out.println("------------------"); char[] chs2 = new char[3]; int len2; while((len2 = reader.read(chs)) !=-1){ String s = new String(chs,0,len2); System.out.println(s); } } }