我有以下任务: 给定以一个长整数开头的文件,该文件告诉您同一文件中单个int数据段的偏移量,编写一个获取该int数据段的类。
ls -l
我有以下任务: 给定以一个长整数开头的文件,该文件告诉您同一文件中单个int数据段的偏移量,编写一个获取该int数据段的类。
ls -l
我认为问题出在这里
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);
}
}
,
来自this post:
在此类中的所有读取例程中,通常来说,如果在读取所需的字节数之前已到达文件末尾,则会引发EOFException(这是一种IOException)。
对于您使用的Object.getPath = function(o,s) {
s = s.replace(/\[(\w+)\]/g,'.$1'); // convert indexes to properties
s = s.replace(/^\./,''); // strip a leading dot
var a = s.split('.');
for (var i = 0,n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
o = o[k];
} else {
return;
}
}
return o;
};
Object.setPath = function(o,p,v) {
var a = p.split('.');
var o = o;
for (var i = 0; i < a.length - 1; i++) {
if (a[i].indexOf('[') === -1) {
var n = a[i];
if (n in o) {
o = o[n];
} else {
o[n] = {};
o = o[n];
}
} else {
// Not totaly optimised
var ix = a[i].match(/\[.*?\]/g)[0];
var n = a[i].replace(ix,'');
o = o[n][ix.substr(1,ix.length-2)]
}
}
if (a[a.length - 1].indexOf('[') === -1) {
o[a[a.length - 1]] = v;
} else {
var ix = a[a.length - 1].match(/\[.*?\]/g)[0];
var n = a[a.length - 1].replace(ix,'');
o[n][ix.substr(1,ix.length-2)] = v;
}
};
函数:
抛出:EOFException-如果此文件在读取四个字节之前到达末尾。
readInt
函数读取4个字节(即32位,整数长度)。
它不会不读取十进制数字并将其解析为整数。
如果您读取的long值正确,则我最好的猜测是,您尝试读取一个数字(例如123)而不是二进制表示形式(123 = 0000 0000 0000 0000 0000 0000 0111 1011)。