Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 449
Ashwin Gupta Avatar asked Jul 12 '15 18:07

Ashwin Gupta


People also ask

How do you read a specific line from a text file in Java?

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.

Which method is used in Java to read line from text file?

You need to use the readLine() method in class BufferedReader .


1 Answers

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();
        //.....
    }
}
like image 140
Misha Avatar answered Oct 06 '22 01:10

Misha