字符流(输入,输出)

输入

import java.io.*;

public class ReaderDemo2 {

    public static void main(String[] args) {

        Reader reader = null;
        try {
            reader = new FileReader("a1.txt");
            //读数据
            int length = 0;
            //定义一个缓冲区
            char[] chars = new char[1024];
            while ((length = reader.read(chars))!= -1) {
                System.out.println(new String(chars, 0, length));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

输出

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

public class WriterDemo {

    public static void main(String[] args) {
        Writer writer = null;
        try {
            writer = new FileWriter("a1.txt");
            //写数据
            writer.write(97);
            writer.write("
wwww.com");
            writer.write("
愿世界没有战争!");
            writer.write(new char[]{你,好,中,国});
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
经验分享 程序员 微信小程序 职场和发展