在此上附加和For循环

时间:2017-07-21 09:36:00

标签: java loops netbeans append

这是我的代码,它告诉IP地址的PING状态。但是,我不能让它使用printstream附加输出,而不是使用如此多的IP地址,我希望使用循环,所以我只使用它一次。 一点帮助将不胜感激。

PrintStream out;
out = new PrintStream(new FileOutputStream("output1.csv"));
System.setOut(out);

String ipAddress = "172.20.10.13";
InetAddress inet = InetAddress.getByName(ipAddress);
System.out.println("Sending Ping Request to " + ipAddress);
System.out.println(inet.isReachable(1000) ? "Host is reachable" : "Host is NOT reachable");

out = new PrintStream(new FileOutputStream("output7.csv"));
System.setOut(out); 

ipAddress = "192.168.1.10";
inet = InetAddress.getByName(ipAddress);
System.out.println("Sending Ping Request to " + ipAddress);
System.out.println(inet.isReachable(1000) ? "Host is reachable" : "Host is NOT reachable");   

out = new PrintStream(new FileOutputStream("output10.csv"));
     System.setOut(out); 

ipAddress = "192.168.1.35";
inet = InetAddress.getByName(ipAddress);
System.out.println("Sending Ping Request to " + ipAddress);
System.out.println(inet.isReachable(1000) ? "Host is reachable" : "Host is NOT reachable");   

2 个答案:

答案 0 :(得分:0)

我认为你想要这样的东西:

PrintStream out = new PrintStream(new FileOutputStream("output.csv", true));
System.setOut(out);

List<String> ipAddresses = Arrays.asList("172.20.10.13", "192.168.1.10", "192.168.1.35");
for (String ipAddress : ipAddresses) {
    InetAddress inet = InetAddress.getByName(ipAddress);
    System.out.println("Sending Ping Request to " + ipAddress);
    System.out.println(inet.isReachable(1000) ? "Host is reachable" : "Host is NOT reachable");
}

传递给true构造函数的FileOutputStream参数告诉您要将新行追加到文件而不是覆盖现有文件。

http://docs.oracle.com/javase/8/docs/api/java/io/FileOutputStream.html#FileOutputStream-java.lang.String-boolean-

答案 1 :(得分:0)

要附加文件而不是覆盖它们,而不是System.setOut使用:

PrintStream writerToFirst = new PrintStream(
 new FileOutputStream("output1.csv", true)); 

然后您可以使用

编写
writerToFirst.append(inet.isReachable(1000) ? "Host is reachable" : "Host is NOT reachable");

感谢:https://stackoverflow.com/a/8043410/6646101