我已经编写了一个端口扫描应用程序,我想将我的控制台输出写入文件,但是发生了一个小问题。 “PrintStream”没有将所有控制台输出写入文件。
例如:try
块中显示控制台中已打开端口的代码不会向文件写入任何内容,而是{{1块写的。
我的代码:
catch
答案 0 :(得分:0)
您有一些与手头问题直接相关的问题。
更新的代码:
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,而是创建一个描述端口状态的数据结构,然后输出(从逻辑单独表示)。 答案 1 :(得分:0)
结果:
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();
}
}
}