JAVA Reading from file word by word using BufferedReader
15,076
After you read line by line:
String line = reader.readLine();
split each line by |
:
String[] words = line.split("\\|");
you can then assign each of these to a descriptive variable, if you'd like:
String year = words[2]
This is the easiest way to do this, though you could have a look at Scanner for something more complicated.
Author by
Liolikas Bramanovas
Updated on June 04, 2022Comments
-
Liolikas Bramanovas almost 2 years
I have to read from a file Author|Name|Year I need to store this information into class nodes. I must use BufferedReader and FileReader.
public class Book { String author, name; int years; } import java.io.FileReader; import java.io.BufferedReader; import java.io.IOException; public class Main { public static void main(String[] args) throws Exception{ Book book1 = new Book(); FileReader file = new FileReader("C:/Users/ZatoIndustries/Desktop/failas.txt"); BufferedReader reader = new BufferedReader(file); String text = ""; String line = reader.readLine(); } }
Input looks like:
A|bbbb|2002 B|cccc|2001 A|dddd|2000
-
VGR about 9 yearsString.split takes a regex. You probably meant that to be
line.split("\\|")
. -
M.Barandov over 2 yearsI have two questions. 1) Shouldn't we use a while loop for reading the entire content of a file with realLine() method? 2) What about if the file we are trying to read has a first line empty? how we should handle that? tnx in advance