有什么方法可以將控制臺輸出鏡像到 java 中的本地主機,甚至可以向其中添加一些不錯的 CSS。如果同一網路中的其他設備也可以訪問控制臺,那就太酷了。我對這個主題做了很多研究,但沒有找到任何關于這個的網站/執行緒/問題。幫助將不勝感激!
uj5u.com熱心網友回復:
為了攔截通常進入控制臺(或標準輸出)的輸出,您需要在代碼中的某處使用以下 API:
System.setOut(myStream);
System.setErr(myStream); //If you want to grab the error stream also. Could go do a different location
許多日志庫已經可以為您做到這一點。但這基本上是您需要捕獲輸出的方式。'myStream' 實際做什么取決于您。將其輸出到 http://localhost:8888 上的 Web 服務器的最快途徑是將輸出定向到一個檔案并啟動 JDK 的嵌入式 Web 服務器。這是您應該能夠運行的示例:
package test.example;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpServer;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class SystemOutToWeb
{
public static void main(String... args ) throws Exception
{
final Path myOutputFile = Paths.get("./MyOutputFile.txt");
final PrintStream myStream = new PrintStream(myOutputFile.toFile());
System.out.println("Going to redirect to : " myOutputFile.toAbsolutePath());
System.setOut(myStream);
System.setErr(myStream);
System.out.println("Starting the Output");
//Have something that logs every 5 seconds
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(() ->
{
System.out.println("Hello - the time is now " Instant.now());
}, 1, 5, TimeUnit.SECONDS);
// Start the simple Java Built in Web Server.
final HttpServer http = HttpServer.create(new InetSocketAddress(8888), 0);
final HttpContext context = http.createContext("/");
context.setHandler(exchange ->
{
byte[] data = Files.readAllBytes(myOutputFile);
exchange.sendResponseHeaders(200, data.length);
OutputStream os = exchange.getResponseBody();
os.write(data);
os.close();
});
http.start();
}
}
如果你給它幾秒鐘的運行時間,那么你應該能夠在 http://localhost:8888 看到一些東西。
當然,這只是起點。例如,您可以一起使用不同的 Web 服務器,或者使用一些 CSS 進一步擴充此資源(甚至可能使用 Web 套接字在檔案更新時將其流式傳輸出去)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/399169.html
上一篇:JS:基本型別和參考型別
