我有以下任务: 给定以单个 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/