PrintStream和PrintWriter

  • PrintStream
package com.io.printstream;

import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;

/**
 * 演示 PrintStream(字节打印流/输出流)
 */
public class PrintStream_ {
    public static void main(String[] args) throws IOException {
        PrintStream out=System.out;
        //在默认情况下,PrintStream输出数据的位置是标准输出,即显示器
        out.println("cyy,hello");
        //因为print底层使用的是write,所以我们也可以直接调用write进行打印/输出
        out.write("cyy,hello".getBytes());
        out.close();

        //我们可以去修改打印流输出的位置/设备
        //"hello,沐晴~"是输出到d:\f1.txt中
        System.setOut(new PrintStream("d:\\f1.txt"));
        System.out.println("hello,沐晴~");
    }
}

 


 

 

 

 

 

  • PrintWriter
package com.io.printstream;

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

public class PrintWriter_ {
    public static void main(String[] args) throws IOException {
        //写入到指定的文件中
        PrintWriter printWriter = new PrintWriter(new FileWriter("d:\\f2.txt"));
        printWriter.print("hi,北京!");
        printWriter.close();

    }
}

 

posted @ 2022-05-04 23:12  胖虎9  阅读(29)  评论(0编辑  收藏  举报