I have a very strange situation: I use a DataInputStream to read a string from a file in UTF8 . If I wrote the read to the file right before it, everything works, and if I just want to read what has already been written down, it falls with an error.
This code works:
private void read() { String path = "/Users/pavel/Desktop/test/target_text.txt"; try (DataOutputStream out = new DataOutputStream(new FileOutputStream(path)); DataInputStream in = new DataInputStream(new FileInputStream(path))) { out.writeUTF("hello"); String data = in.readUTF(); System.out.println(data); } catch (IOException e) { e.printStackTrace(); } } But this does not work anymore:
private void read() { String path = "/Users/pavel/Desktop/test/target_text.txt"; try (DataOutputStream out = new DataOutputStream(new FileOutputStream(path)); DataInputStream in = new DataInputStream(new FileInputStream(path))) { //out.writeUTF("hello"); // причем я только что записывал //этим методом и знаю что записан файл по правилу UTF8 String data = in.readUTF(); System.out.println(data); } catch (IOException e) { e.printStackTrace(); } } Falls with an error:
java.io.EOFException at java.io.DataInputStream.readUnsignedShort(DataInputStream.java:340) at java.io.DataInputStream.readUTF(DataInputStream.java:589) at java.io.DataInputStream.readUTF(DataInputStream.java:564) Please help me understand what my mistake? How can I just read the data using the readUTF() method?