[英]Java : Writing console output to file, Not working
我已經編寫了一個用於端口掃描的應用程序,我想將控制台輸出寫入文件,但是發生了一些小問題。 “ PrintStream”未將所有控制台輸出寫入該文件。
例如: try
塊中的代碼顯示控制台中打開的端口,該代碼不會將任何內容寫入文件,但是catch
塊中的死主機將被寫入。
我的代碼:
public class start {
public static void main(String[] args) throws IOException{
for (int i = 5935; i < 10000; i++){
new test(i);
}
PrintStream printStream = new PrintStream(new FileOutputStream("E:\\ports.txt"));
System.setOut(printStream);
printStream.flush();
}
}
class test implements Runnable{
static String host = "localhost";
int t;
Thread y;
public test(int t2){
t = t2;
y = new Thread(this);
y.start();
}
public void run() {
try {
Socket socket = new Socket(host, t);
System.out.println("Port is alive - " + t);
} catch (IOException e){
System.out.println("Port is dead... - " + t);
}
}
}
您有一些與手頭問題直接相關的問題。
更新的代碼:
class StartPortTester {
public static void main(String[] args) throws IOException, InterruptedException {
// Set up the stream BEFORE starting threads
// This should be in a try-with-resources, or the close done in a finally block.
PrintStream printStream = new PrintStream(new FileOutputStream("ports.txt"));
System.setOut(printStream);
// Start the threads!
List<PortTester> testers = new LinkedList<>();
for (int i = 5935; i < 10000; i++){
testers.add(new PortTester(i));
}
// Wait for the threads to end
for(PortTester t : testers ) {
t.y.join();
}
// Flush (write to disk) and close.
printStream.flush();
printStream.close();;
}
}
class PortTester implements Runnable{
static String host = "localhost";
int t;
Thread y;
public PortTester(int t2){
t = t2;
y = new Thread(this);
y.start();
}
public void run() {
try {
// You should close this either in the finally block or using a try-with-resource.
Socket socket = new Socket(host, t);
System.out.println("Port is alive - " + t);
} catch (IOException e){
System.out.println("Port is dead... - " + t);
}
}
}
這不是完美的
PortTester
編寫System.out,而是創建一個描述端口狀態的數據結構,然后將其輸出(將顯示與邏輯分開)。 結果是:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class start
{
public static void main(String[] args) throws Exception {
try (PrintStream printStream = new PrintStream(new FileOutputStream("E:\\ports.txt"))) {
System.setOut(printStream);
ExecutorService pool = Executors.newCachedThreadPool();
for (int i = 5935; i < 10000; i++) {
final int port = i;
pool.execute(() -> {
try (Socket socket = new Socket("localhost", port)) {
System.out.println("Port is alive - " + port);
}
catch (IOException e) {
System.out.println("Port is dead... - " + port);
}
});
}
pool.awaitTermination(100, TimeUnit.SECONDS);
printStream.flush();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.