0

Using Scanner, i'm not sure how to read a file with multiple lines and store it all into a String. I use a loop like :

while(file.hasNext())
{
    string += file.nextLine();
}

I find that the file.hasNext method eats up all of the data in the file and so file.nextInt() doesn't have any values to find and so it returns and error. What can I do to "reset" the Scanner? I tried creating a new Scanner object but that didn't change anything. I have to run this string through a method and I have run into this problem many times. What should I do?

2
  • Scanner#hasNext() doesn't eat anything, please post a mcve This smells like stackoverflow.com/questions/13102045/… Commented Mar 25, 2016 at 15:54
  • What error did you get? Commented Mar 25, 2016 at 15:54

2 Answers 2

1

Maybe you should try StringBuilder.

StringBuilder builder = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    String line;
    while ((line = br.readLine()) != null) {
    builder.append(line);
    // process the line.
    }
}

later

String text = builder.toString();
Sign up to request clarification or add additional context in comments.

Comments

0

To read the entire contents of a Scanner source into a String, set the Scanner's delimiter to the end of the file:

String contents = file.useDelimiter("\\Z").next();

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.