如何使用字符流进行文件读写

时间:2021-11-16 21:36:16

使用字符流进行读取

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Test01 {
    public static void main(String[] args) {
        int count = 0;
        FileReader reader = null;
        BufferedReader breader = null;
        try {
            reader = new FileReader("F:\\AAA\\info.txt");
            breader = new BufferedReader(reader);
            String temp = "";
            while ((temp=breader.readLine())!=null) {
                System.out.println(temp);
                count++;

            }
            System.out.println("共循环"+count+"次");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                breader.close();
                reader.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}

用字符流写入

package com.lenovo.www;

import java.io.FileWriter;
import java.io.IOException;

public class Test07 {
    public static void main(String[] args) {
        int n = 0;
        try {
            FileWriter writer = new FileWriter("F:\\aaa\\info1.txt");
            writer.write("我爱中国");
            writer.flush();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}