I'm chan beginner for Java developer one of my Interviewer asked this question on Interview I failed and i want to learn this so please share the knowledge if you know. In java need to fetch data from command Prompt and show on console by following tasks
open command prompt run as administrator type ( C:\Windows\system32.netstat -an ) It will show 4 columns like
Proto Local Address Foreign Address State)
TCP 0.0.0.0:135 0.0.0.0:0 LISTENING
TCP 0.0.0.0:445 0.0.0.0:0 LISTENING
TCP 0.0.0.0:554 0.0.0.0:0 LISTENING
UDP 0.0.0.0:3702 *:*
UDP 0.0.0.0:3702 *:*
UDP 0.0.0.0:3702 *:*
like this more line
Task 1 Fetch data from command prompt show on console only the TCP details
TCP 0.0.0.0:135 0.0.0.0:0 LISTENING
TCP 0.0.0.0:445 0.0.0.0:0 LISTENING
TCP 0.0.0.0:554 0.0.0.0:0 LISTENING
Task 2 Fetch data from command prompt show on console only unique local address from Local Address column
0.0.0.0:135
0.0.0.0:445
0.0.0.0:554
0.0.0.0:3702
Task 3 Fetch data from command prompt show on console group by State column and count it
LISTENING = 3
I tried like,whats the exact correct methodology
String s1= null;
String s2= null;
InputStream i=Runtime.getRuntime().exec("netstat -an").getInputStream();
Scanner scan=new Scanner(i).useDelimiter("\\"+"\n"+"\n");
s1=scan.hasNext()?scan.next():null;
List<String> l=new ArrayList<String>();
try {
l.add(s1.replaceAll("Active Connections\r\n"
+ "\r\n"
+ " Proto Local Address Foreign Address State", ""));
for(String a:l) {
System.out.println(a);
}
}catch(Exception e){
e.printStackTrace();
}
You can get the output using Process
class, like below:
ProcessBuilder builder = new ProcessBuilder();
builder.command("cmd.exe", "/c", "netstat -an");
Process process = builder.start();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
Then handling that data is really up to you, there are multiple ways to acheive the goals:
List<String[]> output = reader.lines()
.map(line -> line.trim().split("\\s+"))
.collect(Collectors.toList());
List<String> task1 = output.stream()
.filter(line -> line[0].equals("TCP"))
.map(line -> String.join(" ", line))
.collect(Collectors.toList());
List<String> task2 = output.stream()
.filter(line -> line[0].equals("TCP"))
.filter(line -> distinctByValue(line[1]))
.map(line -> String.join(" ", line))
.collect(Collectors.toList());
I know the tasks solution are not perfect. Those are just a quickly written examples to show how to handle the data from reader
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.