The API docs say the following for readUTF8
Reads in a string from this file. The string has been encoded using a
modified UTF-8 format.
The first two bytes are read, starting from the current file pointer,
as if by readUnsignedShort. This value gives the number of following
bytes that are in the encoded string, not the length of the resulting
string. The following bytes are then interpreted as bytes encoding
characters in the modified UTF-8 format and are converted into
characters.
This method blocks until all the bytes are read, the end of the stream
is detected, or an exception is thrown.
Is your string formatted in this way?
This appears to explain your EOF exceptuon.
Your file is a text file so your actual problem is the decoding.
The simplest answer I know is:
try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("jedis.txt"),"UTF-8"))){
String line = null;
while( (line = reader.readLine()) != null){
if(line.equals("Obi-wan")){
System.out.println("Yay, I found " + line +"!");
}
}
}catch(IOException e){
e.printStackTrace();
}
Or you can set the current system encoding with the system property file.encoding to UTF-8.
java -Dfile.encoding=UTF-8 com.jediacademy.Runner arg1 arg2 ...
You may also set it as a system property at runtime with System.setProperty(...) if you only need it for this specific file, but in a case like this I think I would prefer the OutputStreamWriter.
By setting the system property you can use FileReader and expect that it will use UTF-8 as the default encoding for your files. In this case for all the files that you read and write.
If you intend to detect decoding errors in your file you would be forced to use the I
answered 2012-04-01T14:02:50.997