Reputation: 49
I have Google for a while but I still get confused. When I used FileOutputStream to write some texts into a txt file and then use FileInputStream to read my file, everything was right. But when I typed some words manually to my txt file, and then save in UTF-8 format, I got EOFException. Here is my input code:
StringBuilder s = new StringBuilder();
FileInputStream inputStream = new FileInputStream("filename");
DataInputStream in = new DataInputStream(inputStream);
while (in.available()>0) {
s.append(in.readUTF());
}
in.close();
System.out.println(s);
Upvotes: 0
Views: 465
Reputation: 310883
readUTF()
must have been written by writeUTF()
. Not by FileOutputStream
.writeUTF()
is not a text file. It is a file of sequences of 16-bit length words and strings in a modified encoding, as described in the Javadoc.available() > 0
is not a valid test for end of file.As you state it's a text file, and as your code isn't working, I suggest you should be using BufferedReader.readLine()
. And no ready()
tests. readLine()
will return null at end of stream.
Upvotes: 1
Reputation: 4392
Consider using FileInputStream to read the file, i.e.:
public static void main(String[] args) throws Exception {
StringBuilder s = new StringBuilder();
FileInputStream inputStream = new FileInputStream("file.txt");
int content;
while ((content = inputStream.read()) != -1) {
s.append((char) content);
}
inputStream.close();
System.out.println(s);
}
Upvotes: 0
Reputation: 1306
Javadoc for DataInputStream says the following: "An application uses a data output stream to write data that can later be read by a data input stream". So it is probably not a good idea to read manually-written text from file using DataInputStream.
Consider using FileInputStream#read() method if you need to read bytes or FileReader#read() if you need to read characters.
Upvotes: 0