[英]system.out.println redirection in java
我想捕獲println並重定向到文件並打印
這是我的代碼,我想打印123 / n 456
但這是行不通的,我認為在打印outContent之前我需要一些阻止捕獲的方法,但是我不知道該怎么做。
public static void main(String args[]){
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
System.out.println("123");
System.out.println("456");
System.out.println(outContent.toString());
}
回想過去,在我開始使用log4j或其他專用記錄器之前,我曾經使用一種類似於下面的技術。
本質上,它是一個代理PrintStream
,它將內容回顯到原始PrintStream
並將內容寫入其他一些OutputStream
(例如文件)。
您還可以通過設置為true時不使用old.write(b)
來old.write(b)
將回顯到控制台的標志。 我已使用此技術來停止應用程序向標准輸出中噴出大量廢話,這可能會使應用程序變慢,尤其是在圖形環境中運行時。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
public class RedirectStdOut {
public static void main(String[] args) {
OutputStream os = null;
try {
os = new FileOutputStream(new File("Log.txt"));
LoggingPrintStream lps = new LoggingPrintStream(os);
System.out.println("This is going to the console only...");
lps.install();
System.out.println("This is going to console and file");
System.out.println("Fun times");
lps.uinstall();
System.out.println("This is going to console only...");
} catch (IOException exp) {
exp.printStackTrace();
} finally {
try {
os.close();
} catch (Exception e) {
}
}
}
public static class LoggingPrintStream {
private OutputStream os;
private PrintStream old;
public LoggingPrintStream(OutputStream os) {
this.os = os;
}
public void install() {
old = System.out;
System.setOut(new PrintStream(new OutputStream() {
@Override
public void write(int b) throws IOException {
old.write(b);
os.write(b);
}
}));
}
public void uinstall() throws IOException {
try {
os.flush();
} finally {
try {
os.close();
} catch (Exception e) {
}
System.setOut(old);
}
}
}
}
我試圖弄清楚是否可以束縛溪流,但是今天(星期五下午)我的腦袋還沒完成任務
您應該將out
流重定向到這樣的文件:
System.setOut(new PrintStream(new File("<your log file>"));
這會將您的所有system.out
重定向到日志文件中。 希望這可以幫助。
將System.out.println重定向到Log4J,同時保留類名信息
上面的帖子在某種程度上說明了如何執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.