Use System.setOut()
package io;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class Redirection {
public static void main(String args[]) throws IOException {
PrintStream pos = new PrintStream(new FileOutputStream("applic.log"));
PrintStream oldstream = System.out;
System.out.println("Message 1 appears on console");
System.setOut(pos);
System.out.println("Message 2 appears on file");
System.out.println("Message 3 appears on file");
System.out.println("Message 4 appears on file");
System.setOut(oldstream);
System.out.println("Message 5 appears on console");
System.out.println("Message 6 appears on console");
}
}
package io;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class Redirection {
public static void main(String args[]) throws IOException {
PrintStream pos = new PrintStream(new FileOutputStream("applic.log"));
PrintStream oldstream = System.out;
System.out.println("Message 1 appears on console");
System.setOut(pos);
System.out.println("Message 2 appears on file");
System.out.println("Message 3 appears on file");
System.out.println("Message 4 appears on file");
System.setOut(oldstream);
System.out.println("Message 5 appears on console");
System.out.println("Message 6 appears on console");
}
}
Java输出重定向示例
本文介绍了一个Java程序示例,展示了如何使用System.setOut()方法将标准输出重定向到文件中,同时保留控制台输出的功能。通过创建PrintStream对象并指定目标文件,可以将程序的部分输出写入文件,而不会影响到控制台上的输出。
9560

被折叠的 条评论
为什么被折叠?



