Like the title says, im trying to write a program that can read individual words from a text file and store them to String
variables. I know how to use a FileReader
or FileInputStream
to read a single char
but for what I'm trying to this wont work. Once I input the words I am trying to compare these with other String variables in my program using .equals so it would be best if I can import as Strings. I am also okay with inputting an entire line from a text file as a String in which case Ill just put one word on each line of my file. How do I input words from a text file and store them to String variables?
EDIT: Okay, that duplicate sort of helps. It might work for me but the reason my question is a little different is because the duplicate only tells how to read a single line. Im trying to read the individual words in the line. So basically splitting the line String.
Java supports several file-reading features. One such utility is reading a specific line in a file. We can do this by simply providing the desired line number; the stream will read the text at that location. The Files class can be used to read the n t h nth nth line of a file.
You need to use the readLine() method in class BufferedReader .
These are all really complex answers. And I am sure they are all useful. But I prefer the elegantly simple Scanner
:
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(new File("fileName.txt"));
while(sc.hasNext()){
String s = sc.next();
//.....
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With