3 回答

TA貢獻(xiàn)1802條經(jīng)驗 獲得超5個贊
您可以使用Windows命令行* nix shells支持的輸出流重定向器,例如
java -jar myjar.jar > output.txt
另外,當(dāng)您從vm內(nèi)部運(yùn)行應(yīng)用程序時,可以System.out從java本身內(nèi)部進(jìn)行重定向。您可以使用方法
System.setOut(PrintStream ps)
它將替換標(biāo)準(zhǔn)輸出流,因此所有對System.out的后續(xù)調(diào)用都將轉(zhuǎn)到您指定的流。您可以在運(yùn)行打包的應(yīng)用程序之前執(zhí)行此操作,例如調(diào)用System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("output.txt"))));
如果您使用的包裝程序無法修改,請創(chuàng)建自己的包裝程序。因此,您具有FEST包裝器->流重定向器包裝器->經(jīng)過測試的應(yīng)用程序。
例如,您可以實現(xiàn)一個簡單的包裝器,如下所示:
public class OutputRedirector
{
/* args[0] - class to launch, args[1]/args[2] file to direct System.out/System.err to */
public static void main(String[] args) throws Exception
{ // error checking omitted for brevity
System.setOut(outputFile(args(1));
System.setErr(outputFile(args(2));
Class app = Class.forName(args[0]);
Method main = app.getDeclaredMethod("main", new Class[] { (new String[1]).getClass()});
String[] appArgs = new String[args.length-3];
System.arraycopy(args, 3, appArgs, 0, appArgs.length);
main.invoke(null, appArgs);
}
protected PrintStream outputFile(String name) {
return new PrintStream(new BufferedOutputStream(new FileOutputStream(name)), true);
}
}
您使用3個附加參數(shù)調(diào)用它-要運(yùn)行的Main類,然后輸出/錯誤指示。

TA貢獻(xiàn)1829條經(jīng)驗 獲得超6個贊
使用此構(gòu)造函數(shù)時:
new PrintStream(new BufferedOutputStream(new FileOutputStream(“ file.txt”))));
記住將autoflushing設(shè)置為true,即:
new PrintStream(new BufferedOutputStream(new FileOutputStream(“ file.txt”)),true);
否則,即使程序完成后,您也可能會得到空文件。
添加回答
舉報