CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Aug 2011
    Posts
    22

    Selective retrieval of numbers in a text file

    I have a text file as follows
    Code:
                 total       used       free     shared    buffers     cached
    Mem:          7923       7875         47          0        564       3237
    -/+ buffers/cache:       4074       3848
    Swap:        12287       1067      11220
    Total:       20211       8943      11267
    I have to retrieve only those values which fall in the mem, swap and total under total, used and free i.e. I have to ignore 0, 564, 3237, 4074, 3848. How do I do it?

    I have written the following code to display the all the numbers.
    Code:
    package my.scan;  
    import java.util.*; //importing some java classes  
    import java.lang.*;  
    import java.io.*;  
      
    class ReadFile {
    	void getFile () {
    		int i = 0;
    		
    	       try {  
    	               Scanner myFile = new Scanner(new FileReader("C:/Documents and Settings/shikhau/workspace/SanNumber/freelast.txt"));  
    	               while (myFile.hasNext()) {  
    	                   if (myFile.hasNextInt()) {
    	                	   i = myFile.nextInt();
    	                	   System.out.println(i);
    	                   }
    	                   else {
    	                   		myFile.next();
    	                   }              
    	               }  
    	       }  
    	       catch (FileNotFoundException e){  
    	           System.out.println("Sorry! This file is not found");  
    	       }
    	}
    }
    
    public class ScanNum {  
        public static void main(String[] args) {  
            ReadFile rf = new ReadFile();
        	rf.getFile();
              
        }  
      
    }
    Last edited by shik28; November 23rd, 2011 at 03:27 AM. Reason: BB error

  2. #2
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: Selective retrieval of numbers in a text file

    Check if the line begins with mem, swap or total and ignore any line that doesn't.
    Use split(" +") to break each line into columns.
    Extract the data from the relevant columns.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured