How could Java classes direct program messages to the system console, but error messages, out to a file?
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.IOException;
public class OutToFile {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String fileName = "output.txt";
File file = new File(fileName);
if(!file.exists()){
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(fileName);
PrintStream ps = new PrintStream(fos);
System.setErr(ps);
// System.setOut(ps);
System.out.println("this is a message");
int b = 5/0;
System.out.println(b);
}
}
此时,你会在console中看到信息: this is a message
你会在output.txt文件中看到:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at test.OutToFile.main(OutToFile.java:28)
System.setErr(ps)和System.setOut(ps)都是,加上与否都只写到一个地方,要么console,要么file。