Ashwin Gupta Ashwin Gupta - 1 year ago 62
Java Question

How to read a single word (or line) from a text file Java?

Like the title says, im trying to write a program that can read individual words from a text file and store them to

variables. I know how to use a
to read a single
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?

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.

Answer Source

To read lines from a text file, you can use this (uses try-with-resources):

String line;

try (
    InputStream fis = new FileInputStream("the_file_name");
    InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
    BufferedReader br = new BufferedReader(isr);
) {
    while ((line = br.readLine()) != null) {
        // Do your thing with line

To chunk a line into individual words, you can use String.split:

while ((line = br.readLine()) != null) {
    String[] words = line.split(" ");
    // Now you have a String array containing each word in the current line
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download