【问题标题】:Append and For loop on this在此附加和 For 循环
【发布时间】:2017-12-27 07:15:20
【问题描述】:

这是我的代码,它告诉 IP 地址的 PING 状态。但是,我不能让它使用 printstream 附加输出,而不是使用这么多的 ip 地址,我希望使用 Loop,这样我就不能只使用一次。 一点帮助将不胜感激。

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");   

【问题讨论】:

  • 请在您的问题中添加输出和预期输出。
  • 您能否说得更具体一些。 “我无法让它使用 printstream 附加输出”到底是什么意思?你到底想要什么?将所有数据写入同一个输出文件(output.csv 而不是output1.csvoutput7.csvoutput10.csv)?
  • 只需创建一个函数,将 ipAddress 等内容作为参数传递

标签: java loops netbeans append


【解决方案1】:

要附加文件而不是覆盖它们,而不是 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

【讨论】:

    【解决方案2】:

    我假设你想要这样的东西:

    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");
    }
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-26
      • 2021-08-15
      • 2021-06-24
      • 2020-08-27
      • 2016-12-19
      • 2021-03-03
      • 2012-08-02
      • 2021-04-07
      相关资源
      最近更新 更多