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?

  • `Scanner#hasNext()` doesn't eat anything, please post a [mcve](http://stackoverflow.com/help/mcve) This smells like http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods –  Mar 25 '16 at 15:54
  • What error did you get? – bili Mar 25 '16 at 15:54

2 Answers2

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();
Jakub S.
  • 4,461
  • 35
  • 29
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();
VGR
  • 33,718
  • 4
  • 37
  • 50