我發現了幾個關於如何從System.out和System.err管道和重定向消息的例子。 決定使用JavaFX Webview和Dukescript開發應用程序後,我發現有一個地方可以顯示所有消息,即Firebug Lite控制檯。JavaFX webview:如何將System.out和System.err轉發到Firebug Lite控制檯?
見下文。
PS這是完全相反的作爲this
我發現了幾個關於如何從System.out和System.err管道和重定向消息的例子。 決定使用JavaFX Webview和Dukescript開發應用程序後,我發現有一個地方可以顯示所有消息,即Firebug Lite控制檯。JavaFX webview:如何將System.out和System.err轉發到Firebug Lite控制檯?
見下文。
PS這是完全相反的作爲this
首先定義一個抽象類
public abstract class FirebugConsole extends OutputStream {
abstract void log(String msg);
StringBuilder sb = new StringBuilder();
@Override
public void write(int i) {
sb.append((char)i);
}
@Override
public void flush() {
if(sb.length() >0 && !sb.toString().equals("\r\n"))
log(sb.toString());
sb = new StringBuilder();
}
}
然後用實現本機調用入JavaScript方法擴展它。這裏有一個例子,如何寫日誌消息
public class FirebugConsoleInfo extends FirebugConsole{
@net.java.html.js.JavaScriptBody(args = { "msg" }, body = ""
+ "Firebug.Console.log(msg);")
public native void log(String msg);
}
最後,管System.out和System.err的那些對象
public static void onPageLoad() throws Exception {
...
System.setOut(new PrintStream(new FirebugConsoleInfo(), true));
System.setErr(new PrintStream(new FirebugConsoleError(), true));
...
}
注:因爲某些原因通常console.log()
不爲我工作,我知道如果控制檯對象已經存在,Firebug不會綁定控制檯,所以我懷疑WebFX webview本身必須首先將console.log消息傳遞給System.out。
更新
上述解決方案時不是瀏覽器的其他線程正在生成的消息不起作用。這是基於BrwsrCtx.execute()
public abstract static class FirebugConsole extends OutputStream {
protected final BrwsrCtx ctx;
public FirebugConsole(BrwsrCtx ctx){
this.ctx = ctx;
}
abstract void logNative(String msg);
void log(String msg) {
ctx.execute(new Runnable(){
@Override
public void run() {
logNative(msg);
}
});
}
StringBuilder sb = new StringBuilder();
@Override
public void write(int i) {
sb.append((char)i);
}
@Override
public void flush() {
if(sb.length() >0 && !sb.toString().equals("\r\n"))
log(sb.toString());
sb = new StringBuilder();
}
}
public static class FirebugConsoleInfo extends FirebugConsole{
public FirebugConsoleInfo(BrwsrCtx ctx) {
super(ctx);
}
@net.java.html.js.JavaScriptBody(args = { "msg" }, body = ""
+ "Firebug.Console.log(msg);")
public native void logNative(String msg);
}
public static class FirebugConsoleError extends FirebugConsole{
public FirebugConsoleError(BrwsrCtx ctx) {
super(ctx);
}
@net.java.html.js.JavaScriptBody(args = { "msg" }, body = ""
+ "Firebug.Console.error(msg);")
public native void logNative(String msg);
}
}
和
public static void onPageLoad() throws Exception {
BrwsrCtx ctx = BrwsrCtx.findDefault(GoGPS_Fx.class);
System.setOut(new PrintStream(new FirebugConsoleInfo(ctx), true));
System.setErr(new PrintStream(new FirebugConsoleError(ctx), true));
}
注意更新的解決方案:它是大原木相當緩慢,有可能會更快的替代品(StringWriter的是一個)。但我懷疑瓶頸在於將消息從Java傳遞到JavaScript。