Java 为什么出发不工作?
我试图首先使用setOut写入文件,然后在控制台上重置它以打印helloworld,但它不工作,并且正在写入文件中的所有内容Java 为什么出发不工作?,java,Java,我试图首先使用setOut写入文件,然后在控制台上重置它以打印helloworld,但它不工作,并且正在写入文件中的所有内容 import java.io.*; public class SetOut { public static void main(String s[])throws Exception { FileOutputStream fout=new FileOutputStream("aa.txt"); PrintStream ps =ne
import java.io.*;
public class SetOut {
public static void main(String s[])throws Exception
{
FileOutputStream fout=new FileOutputStream("aa.txt");
PrintStream ps =new PrintStream(fout);
System.setOut(ps);
System.out.println("hello ");
System.out.println("hay");
PrintStream ps4=System.out;
System.setOut(ps4);
System.out.println("hello world");
}
}
这是因为您对
System.SetOut
的第一次调用会用您的文件流覆盖System.out
。您必须在函数开始时保存System.out
的原始值,以便以后恢复
PrintStream ps4=System.out; // save
FileOutputStream fout=new FileOutputStream("aa.txt");
PrintStream ps =new PrintStream(fout);
System.setOut(ps);
System.out.println("hello ");
System.out.println("hay");
System.setOut(ps4); // restore
System.out.println("hello world");