为什么 readLong 方法会导致 EOFException?

why does readLong method cause EOFException?

当我执行下面的代码时,它在第10行抛出eof异常。它似乎无法执行 readLong 方法。我该怎么办?

try (DataOutputStream dataOutputStream=new DataOutputStream(new BufferedOutputStream(new 
FileOutputStream("1.dat")));
         DataInputStream dataInputStream=new DataInputStream(new BufferedInputStream(new 
FileInputStream("C:\Users\Asus\IdeaProjects\Example" +
                 "\1.dat")))){
        dataOutputStream.writeLong(123);
        dataOutputStream.writeChar('D');
        dataOutputStream.writeUTF("Hello!");

        System.out.println(dataInputStream.readLong());//exception occurse here
        System.out.println(dataInputStream.readChar());
        System.out.println(dataInputStream.readUTF());
    }catch (IOException e){
        e.printStackTrace();
    }

您在写入文件之前读取文件的问题。当您阅读文件时,它是空的。在流关闭之前,数据也不会保存到文件中。所以如果你想读取写入的值,你应该关闭输入流然后读取文件。 还要注意输出流文件路径与输入流不同

举个例子:

  try ( DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("1.dat")))) {
        dataOutputStream.writeLong(123);
        dataOutputStream.writeChar('D');
        dataOutputStream.writeUTF("Hello!");
        dataOutputStream.close();
        DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(new FileInputStream("1.dat")));
        System.out.println(dataInputStream.readLong());
        System.out.println(dataInputStream.readChar());
        System.out.println(dataInputStream.readUTF());
    } catch (IOException e) {
        e.printStackTrace();
    }