0

I am trying to read the contents of a file:

Scanner fileReader = new Scanner("myFile.txt");
int counter = 0;
while(fileReader.hasNextLine()) {
    
    if(counter == 0) {
        System.out.println("IT IS READING " + fileReader.nextLine());
    }
}

myFile.txt content:

HELLO WORLD

HELLO WORLD

Instead of printing hello world:

I am getting: IT IS READING myFile.txt

1 Answer 1

3

The problem is that you are initializing a scanner with java.util.Scanner(String) constructor, and this constructor simply creates a Scanner which reads out the String you passed in.

What you actually need is in order to read out a file is:

Scanner fileReader = new Scanner(new File("myFile.txt"));
int counter = 0;
while(fileReader.hasNextLine()) {

    if(counter == 0) {
        System.out.println("IT IS READING " + fileReader.nextLine());
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.