IO流,字符流

 1 import java.io.FileReader;
 2 
 3 public class FileReaderDemo {
 4     public static void main(String[] args) throws Exception{
 5         method_1();
 6         method_2();
 7     }
 8     // 方法一:单个字符读取
 9     public static void method_1() throws Exception{
10         // 1,创建读取字符数据的流对象
11         // 用Reader中的read读取字符。
12         FileReader fr = new FileReader("F://1.txt");
13         int ch = 0;
14         //遍历打印结果
15         while((ch = fr.read()) != -1) {
16             System.out.print((char) ch);
17         }
18         //关闭流
19         fr.close();
20     }
21     // 方法二:使用read(char[])读取文本文件数据
22     public static void method_2() throws Exception{
23         FileReader fr = new FileReader("F://1.txt");
24         char buf[] = new char[1024];
25         int len = 0;
26         //遍历打印结果
27         while((len = fr.read(buf)) != -1) {
28             System.out.println(new String(buf, 0, len));
29         }
30         //关闭流
31         fr.close();
32     }
33 }

猜你喜欢

转载自www.cnblogs.com/LXCG/p/9116153.html
今日推荐