PrintStream
首先我们常用的静态方法System.out.print()就是一个典型的PrintStream ,请看如下代码证明
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException ,ClassNotFoundException{
// 得到printStream
PrintStream out = System.out;
// 打印字符串到默认区域(默认是屏幕)
out.print("Good Morning");
// 关闭
out.close();
}
}
通过查看out.print的源码可以知道底层实际上还是write
还有我们的out.println()的底层实现还有write,只是多个一个换行 。
设置PrintStream打印的位置
通常情况下,我们PrintStream的默认打印位置是屏幕,我们也可以设置PrintStream打印的位置设置为文件。
通过方法 System.setOut()设置打印位置
如下代码实现打印字符到文件
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException ,ClassNotFoundException{
// 得到printStream
PrintStream out = System.out;
// 这里设置了打印位置为a.txt文件
System.setOut(new PrintStream("a.txt"));
// 打印字符串
System.out.println("good morning");
// 关闭
out.close();
}
}
成功的将字符串打印到了a.txt中
PrintWrite
PrintWrite可以说是printStream的一个封装吧
如下例子使用PrintWrite输出到屏幕
import com.mysql.cj.result.Field;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException ,ClassNotFoundException{
// 设置printWriter默认的输出位置是system.out 也就是默认输出位置,屏幕
PrintWriter printWriter = new PrintWriter(System.out);
// 输出字符串
printWriter.println("good pancil");
// 一定要记得关闭,这样才会有效果,具体原因可以自己debug追源码
printWriter.close();
}
}
效果如下
如下例子输出到a.txt文件中
import com.mysql.cj.result.Field;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException ,ClassNotFoundException{
// 设置printWriter默认的输出位置是文件
PrintWriter printWriter = new PrintWriter(new FileWriter("a.txt"));
// 输出字符串
printWriter.println("good pancil");
// 一定要记得关闭,这样才会有效果,具体原因可以自己debug追源码
printWriter.close();
}
}
效果如下