简体   繁体   中英

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.

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

Split() can be used to achieve this eg:

String Line = "item1,item2,item3"
String[] words =Line.split(",");

If you absolutely must know the number of commas, a similar question has already been answered:

Java: How do I count the number of occurrences of a char in a String?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM