打印流

1、打印流基本使用

package demo02;

import org.junit.Test;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;

/**
 * @description: demo10
 * @author: liuyang
 * @create: 2021-09-06 22:27
 */
public class Demo10 {
    /**
     * 重定向System.out打印流
     */
    @Test
    public void test1() {
        FileOutputStream fileOutputStream = null;
        PrintStream ps = null;
        try {
            fileOutputStream = new FileOutputStream("text5.txt");
            ps = new PrintStream(fileOutputStream, true);
            System.setOut(ps);
            System.out.println("hello,我是中国人");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (ps != null) {
                    ps.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 打印流PrintStream
     */
    @Test
    public void test2() {
        FileOutputStream fileOutputStream = null;
        PrintStream ps = null;
        try {
            fileOutputStream = new FileOutputStream("text5.txt");
            ps = new PrintStream(fileOutputStream, true);
            ps.print("你们好");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (ps != null) {
                    ps.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 打印流:PrintWriter
     */
    @Test
    public void test3() {
        FileOutputStream fileOutputStream = null;
        PrintWriter pw = null;
        try {
            fileOutputStream = new FileOutputStream("text5.txt");
            pw = new PrintWriter(fileOutputStream, true);
            pw.print("你们好吗?");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (pw != null) {
                    pw.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

 

posted @ 2021-09-06 22:42  牛牛的自留地  阅读(18)  评论(0编辑  收藏  举报