打印流
打印流(PrintStream)是一个输出流,通常用于将数据打印到控制台或这文件中。最常见的打印流对象是 System.out
。
PrintStream
构造函数:
构造函数 | 描述 |
---|---|
PrintStream(String fileName) | 指定文件名创建打印流,没有自动行刷新 |
PrintStream(File file) | 指定文件创建打印流,没有自动刷新 |
PrintStream(OutputStream out) | 指定OutputStream创建一个新的打印流,没有自动行刷新 |
PrintStream(OutputStream out, boolean autoFlush) | 指定OutputStream创建一个新的打印流,有自动行刷新 |
常见方法:
方法 | 描述 |
---|---|
print(String s) | 打印一个字符串,不带换行 |
println(String s) | 打印一个字符串,带换行 |
java
@Test
public void test() throws FileNotFoundException {
PrintStream ps = new PrintStream("print.txt");
ps.println("斯是陋室");
ps.println("为吾德馨");
ps.print("江山易改");
ps.print("本性难移");
ps.close();
}
也可以使用 System.setOut()
方法 改变输出流流向:
java
@Test
public void test1() throws FileNotFoundException {
// 每次创建新的 PrintStream 对象,文件内容会覆盖
PrintStream ps = new PrintStream("print1.txt");
// 改变输出流流向
System.setOut(ps);
System.out.println("你好");
System.out.println("世界");
ps.close();
}
java
@Test
public void test2() throws FileNotFoundException {
// 通过 FileOutputStream 的 append 属性,实现内容追加
PrintStream ps = new PrintStream(new FileOutputStream("print1.txt", true));
// 改变输出流流向
System.setOut(ps);
System.out.println("你好");
System.out.println("世界");
ps.close();
}