列印流
三個常量:
1.System.in 輸入流
2.System.out 輸出流:調試代碼,列印日志
3.System.err 列印出的顔色是紅色的
重定向
setIn()
setOut()
setErr()
下面為Demo:
public class PrintStreamDemo01 {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("test");
PrintStream ps = System.out;
ps.println(false);
//輸出到檔案
File src = new File("d:/xp/test/print.txt");
ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(src)));
ps.print("io is so easy ...");
ps.close();
}
}
我們可以看到檔案如下:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLzQDO0MzM1cTMyETMxgTMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
然後我們看下面的代碼:
public class SystemDemo01 {
public static void main(String[] args) throws FileNotFoundException {
//test1();
//test2();
//重定向
System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("d:/xp/test/system.txt")), true));
System.out.println("a"); //從控制台轉向檔案
//回控制台
System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.out)),true));
System.out.println("bank...");
}
//檔案輸入
public static void test2() throws FileNotFoundException {
InputStream is = System.in;
is = new BufferedInputStream(new FileInputStream("d:/xp/test/print.txt"));
Scanner sc = new Scanner(is);
System.out.println(sc.nextLine());
}
public static void test1(){
System.out.println("test");
System.err.println("err");
}
}
test1的執行結果為:
我們可以看到,System.err列印到控制台的日志是紅色的,也就是我們平時看到的報錯日志。
test2的執行結果如下:
可以看到,PrintStreamDemo01中輸入到print.txt檔案中的内容被列印輸出到了控制台。
然後main方法中的代碼執行結果如下:
重定向之後 ,我們就可以看到system.txt檔案中内容如下:
在回控制台之後,輸出的内容就會輸出到控制台。
以上為列印流的Demo以及運作結果。