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