0

Can any one suggest, how to use string-tokens in java, to read all data in a file, and display only some of its contents. Like, if i have

apple = 23456, mango = 12345, orange= 76548, guava = 56734

I need to select apple, and the value corresponding to apple should be displayed in the output.

This is the code

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.StringTokenizer;

public class ReadFile {

public static void main(String[] args) {

try { 

String csvFile = "Data.txt";

   //create BufferedReader to read csv file
   BufferedReader br = new BufferedReader(new FileReader(csvFile));
   String line = "";
   StringTokenizer st = null;

   int lineNumber = 0; 
   int tokenNumber = 0;

   //read comma separated file line by line
   while ((line = br.readLine()) != null) {
     lineNumber++;

     //use comma as token separator
     st = new StringTokenizer(line, ",");

     while (st.hasMoreTokens()) {
       tokenNumber++;

       //display csv values
       System.out.print(st.nextToken() + "  ");
     }

     System.out.println();

     //reset token number
     tokenNumber = 0;
   }

  } catch (Exception e) {
   System.err.println("CSV file cannot be read : " + e);
  }
  }   

  }

this is the file I'm working on :

ImageFormat=GeoTIFF
ProcessingLevel=GEO
ResampCode=CC
NoScans=10496
NoPixels=10944
MapProjection=UTM 
Ellipsoid=WGS_84
Datum=WGS_84
MapOriginLat=0.00000000
MapOriginLon=0.00000000
ProdULLat=18.54590200
ProdULLon=73.80059300
ProdURLat=18.54653200
ProdURLon=73.90427600
ProdLRLat=18.45168500
ProdLRLon=73.90487900
ProdLLLat=18.45105900
ProdLLLon=73.80125300
ProdULMapX=373416.66169100
ProdULMapY=2051005.23286800
ProdURMapX=384360.66169100
ProdURMapY=2051005.23286800
ProdLRMapX=373416.66169100
ProdLRMapY=2040509.23286800
ProdLLMapX=384360.66169100
ProdLLMapY=2040509.23286800

Out of this, i need to display only the following : NoScans NoPixels ProdULLat ProdULLon ProdLRLat ProdLRLon

KNU
  • 2,560
  • 5
  • 26
  • 39
  • It really seems like you're asking us to do your work for you. – Sotirios Delimanolis Mar 07 '14 at 06:03
  • read the documentation: http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html – r3ap3r Mar 07 '14 at 06:03
  • 1
    what have you tried so far? If try some stuff and come up against a pretty error that is confusing you, post up! We'll be happy to help :) – WillBD Mar 07 '14 at 06:03
  • Please do not repeat your questions. Isn't this same as your other question? http://stackoverflow.com/questions/22218876/how-to-select-particular-tokens-from-a-file-using-stringtokenizer-in-java – Ean V Mar 07 '14 at 06:04
  • till now, i could read the contents of the file, display it using stringtokenizer. but i'm in a fix, of how to select individual elements from the file. – A V G Sankeerth Mar 07 '14 at 06:06
  • All the names are `comma` separated. So first tokenize the data by using delimiter as `comma` then you will get `apple = 23456`. Now use delimiter as `=` and get the name `apple` and value `23456` at 0 and 1 position respectively. – Amarnath Mar 07 '14 at 06:16
  • at first you say they are comma separated and in the end you show your file content to be line separated. mmm confused – KNU Mar 07 '14 at 06:44
  • @KunalKrishna Sorry about the confusion created. I myself was confused about this thing. – A V G Sankeerth Mar 07 '14 at 06:47
  • so come up with final prblm - comma separated or line separated and we shall give a try – KNU Mar 07 '14 at 06:50
  • @AVGSankeerth ae you are of `split()'function . if not [read about it](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String%29) – KNU Mar 07 '14 at 06:52
  • I have seen that. But, i think it would not help me in my case. – A V G Sankeerth Mar 07 '14 at 06:58

3 Answers3

1
public class Test {

  public String getValue(String str, String strDelim, String keyValueDelim, String key){
      StringTokenizer tokens = new StringTokenizer(str, strDelim);
      String sentence;

      while(tokens.hasMoreElements()){
          sentence = tokens.nextToken();
          if(sentence.contains(key)){
             return sentence.split(keyValueDelim)[1];
          }
       }        
     return  null;
   }

  public static void main(String[] args) {
    System.out.println(new Test().getValue("apple = 23456, mango = 12345, orange= 76548, guava = 56734", ",", "=", "apple"));

  }
}

" I noticed you have edited your question and added your code. for your new version question you can still simply call method while reading the String from the file and get your desire value ! "

M2hp
  • 201
  • 3
  • 11
0

read a complete line using bufferedreader and pass it to stringtokenizer with tokenizer as "="[as you mentioned in your file].

for more please paste your file and what you have tried so far..

ArrayList<String> list = new ArrayList<String>();
list.add("NoScans");
list.add("NoPixels");
list.add("ProdULLat");
list.add("ProdULLon");
list.add("ProdLRLat");
list.add("ProdLRLon");

//read a line from a file.

    while ((line = br.readLine()) != null) {
         lineNumber++;

         //use 'equal to' as token separator
         st = new StringTokenizer(line, "=");
         //check for tokens from the above string tokenizer.
         while (st.hasMoreTokens()) {
         String key = st.nextToken(); //this will give the first token eg: NoScans
         String value = st.nextToken(); //this will give the second token eg:10496

         //check the value is present in the list or not. If it is present then print 
         //the value else leave it as it is.
         if(list.contains(key){
          //display csv values
           System.out.print(key+"="+ " "+value);
           }
         }
Shriram
  • 4,343
  • 8
  • 37
  • 64
  • I have posted the code. Im able to just read and display the contents of the file.... but not able to understand how to do the above mentioned – A V G Sankeerth Mar 07 '14 at 06:22
  • i have mentioned the one which you have pasted. what error r u getting and difficulty you have faced? – Shriram Mar 07 '14 at 06:25
  • i need to read the entire file, and just display some portion of it. not all the data. – A V G Sankeerth Mar 07 '14 at 06:33
  • please provide a sample file. – Shriram Mar 07 '14 at 06:34
  • Add the items[NoScans NoPixels ProdULLat ProdULLon ProdLRLat ProdLRLon] in a list. Pass the line to string tokenizer and check the first token is present in the list. while ((line = br.readLine()) != null) { //use comma as token separator st = new StringTokenizer(line, "="); while (st.hasMoreTokens()) { String key = st.nextToken(); String value = st.nextToken(); if(list.contains(key){ // tokenNumber++; //display csv values System.out.print(st.nextToken() + " "); } } – Shriram Mar 07 '14 at 06:50
  • can u represent it in the form of a code?? I'm new to java. so not that fluent in understanding the logics. – A V G Sankeerth Mar 07 '14 at 06:53
0

I have written code assuming you have already stored data from file to a String,

public static void main(String[] args) {
    try {
        String[] CONSTANTS = {"apple", "guava"};
        String input = "apple = 23456, mango = 12345, orange= 76548, guava = 56734";
        String[] token = input.split(",");

        for(String eachToken : token) {
            String[] subToken = eachToken.split("=");
            // checking whether this data is required or not. 
            if(subToken[0].trim().equals(CONSTANTS[0]) || subToken[0].trim().equals(CONSTANTS[1])) {
                System.out.println("No Need to do anything");
            } else {
                System.out.println(subToken[0] + " " + subToken[1]);
            }
        }
    } catch(Exception e) {
        e.printStackTrace();
    }
}
Amarnath
  • 8,736
  • 10
  • 54
  • 81
  • is there any other way to store to data from a file to string other than copying it in input file? Because, my file is very large. – A V G Sankeerth Mar 07 '14 at 06:28
  • Just do it in chunks .. never ever read entire data from file. – Amarnath Mar 07 '14 at 06:29
  • Can we read the entire file line by line, and using if conditions, can we display the values? – A V G Sankeerth Mar 07 '14 at 06:31
  • Yes we should do that .. instead of reading the whole file. See [this](http://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-using-java) for more details. – Amarnath Mar 07 '14 at 06:33
  • That was helpful. But,how to select and display only some part of the entire file?? – A V G Sankeerth Mar 07 '14 at 06:35
  • I can only answer if I know what exactly is the data representation format in the file and .. what is that **some part** you are talking about? – Amarnath Mar 07 '14 at 06:37
  • I have edited my answer .. we already know what information we need to extract from the available data.So we will flag them and check when ever we read a line from the file and print accordingly. – Amarnath Mar 07 '14 at 06:48
  • In the above code look at CONSTANTS variable, it is used to store the flags that we require to extract. In your case you will need to store `NoScans NoPixels ProdULLat ProdULLon ProdLRLat ProdLRLon` and check every time when you read a line from file. – Amarnath Mar 07 '14 at 06:54
  • you mean, checking by using if condition?? – A V G Sankeerth Mar 07 '14 at 06:56
  • Yes. For the time being that is what I have done .. if you know some other way .. you can try those. – Amarnath Mar 07 '14 at 06:59