[英]Checking if 'stderr' is empty in a Java program
有沒有一種方法可以在Java程序中檢查到那時stderr
是否已打印了什么? 作為一個虛擬的例子,
if (something == somethingElse)
{
System.err.println("This is a message");
}
// Here, I want to check if stderr is empty, or if something was printed to it
當然,這是可能的(盡管建議僅作為測試設置的一部分,而不作為應用程序本身的一部分)。
您可以將System.err
重定向到另一個PrintStream
。 如果該PrintStream
在緩沖區中捕獲了輸出,則可以稍后檢查該緩沖區。
如果您還想按照@ElliotFrisch的建議查看原始錯誤流上的輸出,那么您需要做更多的工作:您需要制作一個自定義PrintStream子類,該子類將輸出定向到原始System.err和緩沖區。 。
但是,如果這只是為了捕獲單元測試的輸出,則可能不需要它-您可能想斷言輸出中包含某些內容。
// Set up alternate System.err PrintStream that prints to a buffer
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
PrintStream p = new PrintStream(bytes, true, "UTF-8");
System.setErr(p);
if (something == somethingElse) {
System.err.println("This is a message");
}
// Here, I want to check if stderr is empty, or if something was printed
// to it
// Capture what was printed so far
String printedSoFar = bytes.toString("UTF-8");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.