IO流

 

抽象基类    文件流        缓存流

InputStream  FileInputStream     BufferedInputStream
OutputStream FileOutputStream     BufferedOutputStream
Reader    FileReader        BufferedReader
Writer      FileWriter        BufferedWriter

转换流 

InputStreamReader:将一个字节的输入流转换为字符的输入流

OutputStreamWriter:将一个字符的输出流转换为字节的输出流

 

 

FileReader字符流读取文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Test
    public void test(){//FileReader读取文件
        FileReader fr = null;
        try {
            //1.实例化File类的对象,指明要操作的文件
            File file = new File("hello.txt");//单元测试方法中,文件路径相对于当前module;main方法中路径相对当前工程下
            //2.提供具体的流
            fr = new FileReader(file);
            //3.数据的读入,read():返回读入的一个字符,如果达到文件末尾,返回-1
            int data ;
            while ((data=fr.read())!=-1){
                System.out.print((char)data);//一个字符一个字符的读
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //4.流的关闭
            try {
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
 
    }

  

FileReader中使用read(char[] cbuf)读入数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@Test
    public void test2(){//FileReader读取文件
        FileReader fr = null;
        try {
            //1.实例化File类的对象,指明要操作的文件
            File file = new File("hello.txt");
            //2.提供具体的流
            fr = new FileReader(file);
            //3.数据的读入,read(char[] cbuf):返回每次读入cbuf数组中的字符的个数,如果达到文件末尾,返回-1
            char[] cbuf = new char[5];
            int len ;
            while ((len=fr.read(cbuf))!=-1){
                System.out.print(new String(cbuf,0,len));//一此读取5个字符
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //4.流的关闭
            try {
                if(fr!=null)
                  fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
 
    }

  

 

posted @   iTao0128  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示