コンソール/標準出力に文字列を出力する関数を呼び出しています。この文字列をキャプチャする必要があります。印刷を実行している関数を変更したり、継承によって実行時の動作を変更したりすることはできません。これを可能にする事前定義されたメソッドを見つけることができません。
JVMは印刷されたコンテンツのバッファを保存しますか?
誰かが私を助けるJavaメソッドを知っていますか?
を呼び出すことにより、標準出力をリダイレクトできます
System.setOut(myPrintStream);
または-実行時にログに記録する必要がある場合は、出力をファイルにパイプします。
java MyApplication > log.txt
別のトリック-リダイレクトしたいがコードを変更できない場合:アプリケーションを呼び出すクイックラッパーを実装し、それを開始します:
public class RedirectingStarter {
public static void main(String[] args) {
System.setOut(new PrintStream(new File("log.txt")));
com.example.MyApplication.main(args);
}
}
System.errまたはSystem.outを、文字列バッファーに書き込むストリームに一時的に置き換えることができます。
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class RedirectIO
{
public static void main(String[] args)
{
PrintStream orgStream = null;
PrintStream fileStream = null;
try
{
// Saving the orginal stream
orgStream = System.out;
fileStream = new PrintStream(new FileOutputStream("out.txt",true));
// Redirecting console output to file
System.setOut(fileStream);
// Redirecting runtime exceptions to file
System.setErr(fileStream);
throw new Exception("Test Exception");
}
catch (FileNotFoundException fnfEx)
{
System.out.println("Error in IO Redirection");
fnfEx.printStackTrace();
}
catch (Exception ex)
{
//Gets printed in the file
System.out.println("Redirecting output & exceptions to file");
ex.printStackTrace();
}
finally
{
//Restoring back to console
System.setOut(orgStream);
//Gets printed in the console
System.out.println("Redirecting file output back to console");
}
}
}