[英]In RandomAccessFile why is 0 the first position and 8 the fourth?
这是我的程序,
public class RandomAccessDemo {
public static void main(String[] args) {
double data[] = { 19.4, 10.1, 123.54, 33.0, 87.9, 74.25 };
double d;
// open and use a random access file
try (RandomAccessFile raf = new RandomAccessFile("random", "rw")) {
// write values to the file
for (int i = 0; i < data.length; i++) {
raf.writeDouble(data[i]);
}
// now read back specific values
raf.seek(0);// seek to first double
d = raf.readDouble();
System.out.println("First Values is " + d);
raf.seek(8);// seek to first double
d = raf.readDouble();
System.out.println("Second Values is " + d);
raf.seek(8 * 3);// seek to first double
d = raf.readDouble();
System.out.println("Fourth Values is " + d);
System.out.println();
// Now read every other value
System.out.println("Here is every other value:");
for (int i = 0; i < data.length; i += 2) {
raf.seek(8 * i);// seek to ith double
d = raf.readDouble();
System.out.println(d + " ");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我想知道为什么0是第一个位置,8是第二个值,而8 * 3是第四个值? 这些数字对应什么? 另外,当将数据写入“随机”时,java是否会创建一个名为random的文件? 我没有创建文本文件,所以此随机文件存储在哪里?
位置以字节为单位; 0是第一个字节,1是第二个字节,依此类推。双精度数每个都是8字节,因此这就是为什么您获得8x行为的原因。
在这种情况下,“随机”一词并不意味着它是一个随机文件,而是可以随时访问文件的任何部分(相对于始终必须从头开始并且只能向前)。 从系统的角度来看,您可以随意偏移访问文件。 文件本身可以在任何地方,传递给构造函数的参数指定其路径。
对于第一个问题,随机访问文件允许对文件的内容进行非顺序或随机访问。 要随机访问文件,请打开文件,查找特定位置,然后从该文件读取或写入该文件。 同样,它以字节为单位进行测量,这是8位,这就是为什么它变为0、8、8 * 2等。
对于第二个问题,“随机”应该是文件名的位置。 如果要在D:驱动器上写入文件,则应创建“ D:\\ random.txt”,它将在D:驱动器位置生成random.txt文件。 如果仅创建“ D:\\ random”,是的,它将创建一个随机文件,但是缺少哪种文件类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.