我是Java的初学者,在我的代码中,我正在执行一个Dos命令,它给了我输出。从我想知道如何将一个句子分成两部分,我在这篇文章中附加了我的代码和输出
查看我的代码
import java.io.*;
import java.util.*;
public class NetStat {
public static void main(String[] args) {
try
{
Process p=Runtime.getRuntime().exec("netstat -an");
BufferedReader rd=new BufferedReader(new InputStreamReader(p.getInputStream()));
String lines=rd.readLine();
while(lines != null)
{
System.out.println(lines);
lines=rd.readLine();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
上述代码的输出为:
Active Connections
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:1052 0.0.0.0:0 LISTENING
TCP 0.0.0.0:1053 0.0.0.0:0 LISTENING
TCP 0.0.0.0:3389 0.0.0.0:0 LISTENING
TCP 0.0.0.0:7077 0.0.0.0:0 LISTENING
TCP 192.168.8.254:139 0.0.0.0:0 LISTENING
TCP 192.168.8.254:1097 192.168.10.100:1433 ESTABLISHED
TCP 192.168.8.254:1098 192.168.10.100:1433 ESTABLISHED
TCP 192.168.8.254:1099 192.168.10.100:1433 ESTABLISHED
TCP 192.168.8.254:1110 192.168.10.100:1433 ESTABLISHED
TCP 192.168.8.254:2341 192.168.8.120:8014 ESTABLISHED
TCP 192.168.8.254:2342 192.168.8.254:7077 TIME_WAIT
TCP [::]:135 [::]:0 LISTENING 0
TCP [::]:1052 [::]:0 LISTENING 0
TCP [::]:13600 [::]:0 LISTENING 0
UDP 0.0.0.0:161 *:*
UDP 0.0.0.0:445 *:*
UDP 0.0.0.0:500 *:*
UDP 0.0.0.0:1048 *:*
UDP 0.0.0.0:4500 *:*
UDP 127.0.0.1:123 *:*
UDP 127.0.0.1:1026 *:*
UDP 127.0.0.1:1049 *:*
UDP 127.0.0.1:1061 *:*
UDP 127.0.0.1:1101 *:*
UDP 127.0.0.1:1120 *:*
UDP 127.0.0.1:1900 *:*
UDP 192.168.8.254:123 *:*
UDP 192.168.8.254:137 *:*
UDP 192.168.8.254:138 *:*
UDP 192.168.8.254:1900 *:*
我想将输出分成两部分,如下面的
Split ted part 1= [TCP 0.0.0.0:135 0.0.0.0:0]
Split ted part 2= [LISTENING]
请分享您的想法!...
答案 0 :(得分:0)
像这样的可能适合你:
public static void main(String[] args) {
String s = "TCP 0.0.0.0:135 0.0.0.0:0 LISTENING";
String[] arr = s.split("\\s+(?=[A-Z]+)");
System.out.println(Arrays.toString(arr));
System.out.println(arr.length);
System.out.println("part1 : "+ arr[0]);
System.out.println("part2 : "+ arr[1]);
}
O / P:
[TCP 0.0.0.0:135 0.0.0.0:0, LISTENING]
2
part1 : TCP 0.0.0.0:135 0.0.0.0:0
part2 : LISTENING
答案 1 :(得分:0)
你也可以试试这个,
String s = " TCP 0.0.0.0:135 0.0.0.0:0 LISTENING\n" +
" TCP 0.0.0.0:445 0.0.0.0:0 LISTENING\n" +
" TCP 0.0.0.0:1052 0.0.0.0:0 LISTENING\n" +
" TCP 0.0.0.0:1053 0.0.0.0:0 LISTENING\n" +
" TCP 0.0.0.0:3389 0.0.0.0:0 LISTENING\n" +
" TCP 0.0.0.0:7077 0.0.0.0:0 LISTENING\n" +
" TCP 192.168.8.254:139 0.0.0.0:0 LISTENING";
String parts[] = s.split("\n");
for (String i: parts)
{
String[] f= i.split("\\s+(?=\\S+$)");
String part1 = f[0];
String part2 = f[1];
System.out.println(part1);
System.out.println(part2);
}
输出:
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:1052 0.0.0.0:0
LISTENING
TCP 0.0.0.0:1053 0.0.0.0:0
LISTENING
TCP 0.0.0.0:3389 0.0.0.0:0
LISTENING
TCP 0.0.0.0:7077 0.0.0.0:0
LISTENING
TCP 192.168.8.254:139 0.0.0.0:0
LISTENING