Reputation: 7840
Hi I have text file which contain given below
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
23876 root 20 0 9436 1764 760 R 4 0.0 0:00.08 top
50741 hcsadm 20 0 18.0g 2.3g 751m S 4 0.4 1310:10 hdbnameserver
51089 hcsadm 20 0 55.0g 48g 23g S 4 9.5 4713:14 hdbindexserver
15618 gdm 20 0 273m 65m 11m S 2 0.0 162:17.68 gdm-simple-gree
15938 cisadm 20 0 687m 281m 267m S 2 0.1 306:55.97 hdb.sapCIS_HDB0
17645 hbsadm 20 0 18.1g 7.7g 598m S 2 1.5 974:48.98 hdbnameserver
17795 hbsadm 20 0 109g 104g 39g S 2 20.8 14496:26 hdbindexserver
and my java code reading file as given below
Scanner sc = new Scanner(new File("top.txt"));
while(sc.hasNext()){
String line = sc.nextLine();
}
Now any one knows how to I translate file data in following format
array=[{PID:23876,USER:root,COMMAND:top},{PID:50741,USER:hcsadm,COMMAND:hdbnameserver},..........]
How I used regular expression in java so I convert my file info in above format or there are any other options in java to make above array.
Upvotes: 3
Views: 853
Reputation: 53525
Try:
while(sc.hasNext()){
String line = sc.nextLine();
String[] values = line.split("\\s+");
String PID = "PID":+values[0];
String USER = "USER:"+values[1];
String COMMAND = "COMMAND:"+values[11];
//now do whatever you want with it, for example
String [] res = {PID, USER, COMMAND};
}
Upvotes: 2
Reputation: 4600
Just split each line.
String[] fields = line.split("\\s+"); // split based on whitespace characters
String PID = fields[0];
String USER = fields[1];
String COMMAND= fields[11];
Upvotes: 2