0

This is my code which tells the status of PING of an IP address. However, I cannot get it to append the output using printstream and instead of using so many ip addresses I wish to use Loop so that i have t use it just once. A little help would be appreciated.

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");   
Luciano van der Veekens
  • 6,307
  • 4
  • 26
  • 30
  • 1
    please add output and expected output in your question. – Ravi Jul 21 '17 at 09:40
  • Could you please be more specific. What exactly do you mean with "I cannot get it to append the output using printstream"? What exatly do you want? Write all data to the same output file (`output.csv` instead of `output1.csv`, `output7.csv` and `output10.csv`)? – Alexander Jul 21 '17 at 09:40
  • Just create a function where you pass things like ipAddress etc as parameter – Christian Jul 21 '17 at 09:41

2 Answers2

0

I assume you want something like this:

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

The true argument passed to the constructor of FileOutputStream tells it you want to append new lines to the file instead of overwriting existing ones.

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

Luciano van der Veekens
  • 6,307
  • 4
  • 26
  • 30
0

To append the files instead of overwriting them, instead of System.setOut use:

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

and then you can write by using

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

Credit to: https://stackoverflow.com/a/8043410/6646101

Ahmad sibai
  • 147
  • 2
  • 4