Search code examples
javajava.util.scannerbufferedreader

Reading a line from a text file Java


I am trying to read a line from a file using BufferedReader and Scanner. I can create both of those no problem. What I am looking to do is read one line, count the number of commas in that line, and then go back and grab each individual item. So if the file looked like this:

item1,item2,item3,etc.

item4,item5,item6,etc.

The program would return that there are four commas, and then go back and get one item at a time. It would repeat for the next line. Returning the number of commas is crucial for my program, otherwise, I would just use the Scanner.useDelimiter() method. I also don't know how to return to the beginning of the line to grab each item.


Solution

  • Why not just split the String. The split method accepts a delimiter (regex) as an argument and breaks the String into a String[]. This will eliminate the need to return to the beginning.

    String value = "item1,item2,item3";
    String[] tokens = value.split(",");
    

    To get the number of commas, just use, tokens.length - 1

    String.split() Documentation