3

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.

3
  • Do you want a JSON string that represents the file contents? Or is your proposed output a conceptual representation of a Java data structure? Because arrays don't look like that in Java. Commented Sep 18, 2013 at 7:32
  • @TedHopp Hi, actually I want json string so I insert that json string in mongo. Commented Sep 18, 2013 at 13:44
  • Use one of the posted solutions to parse each line (skipping the first line, of course) and use a JSON library to build the appropriate JSON structures. If you have J2EE 7, you can use the classes in javax.json. Alternatively, you can use a third-party package like the lightweight json-simple or the popular JSON in Java library. Many other Java libraries are listed at json.org. Commented Sep 18, 2013 at 18:05

2 Answers 2

2

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];
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.