DataInputStream.readUTF
is not suitable for reading text files.
It is actually designed for reading character strings that have been embedded in (binary) data files. What the method expects is a 2 byte binary unsigned integer which gives the length (in bytes) of the UTF encoded string. This is followed by the bytes of "modified UTF-8" data. See the following links for more details:
If you try to use DataInputStream.readUTF()
to read a regular text file, it will misinterpret the first 2 characters in the file as a byte count and then attempt to read that number of bytes. Depending on the (supposed) count and the file size, that is liable to attempt to read past the end of the file ... resulting in an EOF exception.
Here are some Q&A's that explain some of the correct ways to read text from a text file:
But note that none of them involve DataInputStream
. That class is for reading binary data files, not text files.