# 列印流 PrintStream 和 PrintWriter ![](https://img2023.cnblogs.com/blog/3008601/202306/3008601-20230604103522664-997405676.png) ![](https://img2023.cnblo ...
列印流
PrintStream 和 PrintWriter
import java.io.IOException;
import java.io.PrintStream;
/**
* @author: 86199
* @date: 2023/5/7 21:17
* @description: 演示位元組列印流/輸出流 PrintStream
*/
public class PrintStream_ {
public static void main(String[] args) throws IOException {
//System.out 在 Java 中也是一個 final 對象引用,
// 但它的初始化是在 Java 虛擬機啟動時完成的,被初始化為一個指向標準輸出流的對象。
//指向的地址不能修改,這個指向的對象本身可以被修改
PrintStream out = System.out;
//在預設情況下,PrintStream 輸出數據的位置是 標準輸出 即顯示器
out.print("Hello World!");
//因為print()的底層本身就是write(),所以我們可以直接調用write()進行列印/輸出
/* 源碼
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
*/
out.write("Hello World!".getBytes());
out.close();
//我們可以修改列印流輸出的位置/設備
System.setOut(new PrintStream("e:\\f1.txt"));
System.out.println("Hello World!");//會輸出到文件中
/*
public static void setOut(PrintStream out) {
checkIO();
setOut0(out);//native方法,修改了out
}
*/
}
}
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @author: 86199
* @date: 2023/5/7 21:51
* @description: 演示 PrintWriter 使用方式
*/
public class PrintWriter_ {
public static void main(String[] args) throws IOException {
// PrintWriter printWriter = new PrintWriter(System.out);
PrintWriter printWriter = new PrintWriter(new FileWriter("e:\\f2.txt"));
printWriter.print("三國演義 very good!");
//不關閉流數據就不會輸出
printWriter.close();
}
}