Java的字符流

Java的字符流

字符输入流

package com.cnblogs;

import java.io.*;

/*
本类用于测试字符流的读取
 */
public class TestIn2 {
    public static void main(String[] args) {
//        method();//普通
        method2();//高效
    }

    private static void method() {
//        Reader in2 = new Reader();    抽象的
        Reader in2 = null;
        try {
            in2 = new FileReader("E:\\ready\\1.txt");
            int result = 0;
            while((result = in2.read()) != -1){
                System.out.println(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                in2.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void method2() {
        Reader in2 = null;
        try {
            in2 =new BufferedReader(new FileReader("E:\\ready\\1.txt"));
            int result = 0;
            while((result = in2.read()) != -1){
                System.out.println(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                in2.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

字符输出流

package com.cnblogs;

import java.io.*;

/*
本类用于测试字符输出流
 */
public class TestOut2 {
    public static void main(String[] args) {
        method();
//        method2();
    }

    private static void method() {
        Writer out2 = null;
        try {
            String date = "hello World!!!";
            out2 = new FileWriter("E:\\ready\\1.txt",true);
//            out2.write(99);
//            out2.write(99);
//            out2.write(99);
//            out2.write(99);
//            out2.write(99);
            out2.write(date);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out2.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void method2() {
        Writer out2 = null;
        try {
            out2 =new BufferedWriter(new FileWriter("E:\\ready\\1.txt",true));
            out2.write(98);
            out2.write(98);
            out2.write(98);
            out2.write(98);
            out2.write(98);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out2.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

posted @ 2021-07-17 09:56  贪玩的阿柒  阅读(42)  评论(0编辑  收藏  举报