java - 为什么我会出现 java.io.EOFException?

标签 java io

我有以下任务: 给定以单个 long 开头的文件,该文件告诉您同一文件中单个 int 数据的偏移量,请编写一个获取 int 数据的类。

try {
        long dataPosition = 0;
        int data = 0;
            RandomAccessFile raf = new RandomAccessFile("datafile.txt", "r");

        //Get the position of the data to read.
        dataPosition = raf.readLong();

        //Go to that position.
        raf.seek(dataPosition);

        //Read the data.
        data = raf.readInt();
        raf.close();

        //Tell the world.
        System.out.println("The data is: " + data);

    } catch (FileNotFoundException e) {
        System.err.println("This shouldn't happen: " + e);
    } catch (IOException e) {
        System.err.println("Writing error: " + e);
    }
    }

最佳答案

我认为问题出在这里:

dataPosition = raf.readLong();

您应该从控制台读取位置,而不是从文件中读取位置。

改用这个:

Scanner scr=new Scanner(System.in);
dataPosition = scr.nextLong();

完整代码:

try {
        long dataPosition = 0;
        int data = 0;
        RandomAccessFile raf = new RandomAccessFile("datafile", "r");

        //Get the position of the data to read.
        Scanner scr=new Scanner(System.in);
        dataPosition = scr.nextLong();

        //Go to that position.
        raf.seek(dataPosition);

        //Read the data.
        data = raf.readInt();
        raf.close();

        //Tell the world.
        System.out.println("The data is: " + data);

    } catch (FileNotFoundException e) {
        System.err.println("This shouldn't happen: " + e);
    } catch (IOException e) {
        System.err.println("Writing error: " + e);
    }
    }

关于java - 为什么我会出现 java.io.EOFException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58899571/

相关文章:

java - Ping 结果的正则表达式模式匹配

java - 如何阻止 ActionListener 停止所有其他代码?

python - 文件 i/o 和二进制模式的含义

.net - 防止 IO.GetDirectories() 遵循符号链接(symbolic link)

c++ - 从文件c++中将单个字符读入变量

python - 无需执行即可从文件中读取列表和字典

java - 旋转后用 ProgressBar 更新 ProgressDialog

java - 是否可以在单独的类中定义场景?

c - C 中函数读取文件的意外行为

java - 基于时间的线程安全优先级队列