Skip to content
Advertisement

How can I get Java to read all text in file?

I am trying to get Java to read text from a file so that I can convert the text into a series of ascii values, but currently it only seems to be reading and retrieving the first line of the txt file. I know this because the output is much shorter than the text in the file.

The text in the file is below:

JavaScript

I think because each line of text has an empty line between them the program is only reading the first line then stopping when it sees there is no line after it, but in facts 2 lines down instead.

Here is the code I have written:

JavaScript

I have commented in the code where I think the issue is. The first while condition checks whether there is a next line by using the hasNextLine(), I have tried using the method ReadAllLines() but it says this method is undefined for the type scanner.

How can I get the program to read and retrieve the entire text file instead of the first line?

Thanks!

Advertisement

Answer

To read the entire input stream:

JavaScript

then just:

JavaScript

This works by setting the token delimiter to start of all input, which of course is never encountered after any byte read, so the “next” token is the entire input.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement