-3

My text file is like:

1, gold, silver, truck
2, gold, fire, truck
3, china, asia, gold, silver, truck, truck
4, ireland, spain, prague, paris

How to jump the first element of the line (1,2,3,4) and read rest of the word one by one?

And how to read only the first element of a row?

Cause I need to store them separatly into two HashMaps.

Thx

GeorgeG
  • 11
  • 1
  • 6

5 Answers5

1

You read the file line by line and split each line at the commas. This gives you a String[]. The first Element in that Array is the number, the others are the words.

quantumbyte
  • 503
  • 1
  • 6
  • 13
0

I think that You need to read the file line by line, so try this:

BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
   // do stuff
}
br.close();

and if you want to skip the first element add this code before the while loop.

br.readLine();//to skip the first line
Salah
  • 8,567
  • 3
  • 26
  • 43
0

you can read file line by line and use string tokenizer: StringTokenizer st = new StringTokenizer(String readline, String ","); Check this

StackExploded
  • 539
  • 7
  • 17
0

You can read separate the tokens with comma and read token by token:

Scanner sc = new Scanner(new File("myfile.txt"));
sc.useDelimiter(",|$");

int lineNumber = 1;
String lineNumberStr = String.valueof(lineNumber);

while (sc.hasNext()) {

    String token = sc.next();

    if (toekn.equals(lineNumberStr)) {
        ++lineNumber;
        lineNumberStr = String.valueof(lineNumber);
        continue;
    } // if

    putWordIntoMyHashMap(token);
} // while
selalerer
  • 3,766
  • 2
  • 23
  • 33
-1

Have you looked at commons-csv? http://commons.apache.org/proper/commons-csv/

Ray
  • 3,084
  • 2
  • 19
  • 27
  • I think the simple task the OP wants to implement can be easily done without a library. I feel like that would be overkill. – quantumbyte Mar 12 '14 at 13:21