简体   繁体   English

使用DataInputStream.readUTF读取String时的java.io.EOFException

[英]java.io.EOFException at using DataInputStream.readUTF to read String

I'm stuck on a part of a project code written in Java. 我陷入了用Java编写的项目代码的一部分。 The problem is every time the following method is called: 问题是每次调用以下方法时:

public static void printData(File f,int n){

   try {
       DataInputStream dis = new DataInputStream(new FileInputStream(f));
       for (int i = 0; i < 5; i++) {
        System.out.println(dis.readUTF());
       }

       dis.skipBytes(43*(n-10));

       for (int i = 0; i < 5; i++) {
        System.out.println(dis.readUTF());
       }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

The code crushes throwing an EOFException every time I try to skip a certain number of bytes, in other words, the program stops when it tries to read again in the second FOR loop (the first one works fine), but it seems it related to the skipBytes method... But I don't see clearly what is causing this. 每次我尝试跳过一定数量的字节时,代码都会抛出EOFException异常,换句话说,当程序尝试在第二个FOR循环中再次读取时,程序停止运行(第一个工作正常),但似乎与skipBytes方法...但是我不清楚原因是什么。 Any little help is welcome. 欢迎任何帮助。

By the way, 43 is the number of bytes of each line, and n (2^9) is the number of lines written in f. 顺便说一下,43是每行的字节数,n(2 ^ 9)是写在f中的行数。

See docs of DataInputStream.readUTF() method. 请参阅DataInputStream.readUTF()方法的文档。 It throws EOFException if: 如果出现以下情况,它将引发EOFException:

EOFException - if this stream reaches the end before reading all the bytes.

So, you read all bytes already or you skipped them at 因此,您已经读取了所有字节,或者在以下位置跳过了它们

dis.skipBytes(43*(n-10));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM