关于RandomAccessFile中的seek(long pos)方法?
import java.io.*;
public class ReadRandom
{
public static String readLine() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
return br.readLine();
}
public static int getRecordNumber() throws IOException, NumberFormatException
{
System.out.println( "Record number (-1 to quit)? ");
return Integer.parseInt(readLine());
}
public static void main(String[] args)
{
int dataSize; // Number of elements in File
int rn; // Record number
double value; // Value of requested record
int sizeOfInt = 4; // size of int variable
int sizeOfDouble = 8; // size of double variable
boolean wantsToQuit = false;
try
{
File fi = new File( "Data.bin ");
RandomAccessFile rin = new RandomAccessFile(fi, "r ");
dataSize = rin.readInt();
System.out.println( "\nFile has " + dataSize + " elements\n ");
while (!wantsToQuit)
{
rn = getRecordNumber();
wantsToQuit = (rn == -1);
if (!wantsToQuit)
{
rin.seek(sizeOfInt + rn * sizeOfDouble); // MARK!!!!!!!!!!!!!
value = rin.readDouble();
System.out.println( "record " + rn + " = " + value);
}
}
}
catch (IOException e)
{
System.err.println(e);
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
请问各位高手这个seek(sizeOfInt + (rn * sizeOfDouble))中的为什么这么计算文件的中的指针定位,还有这里的参数计算结果怎么是整型的,doc文档的好象是long型的,这也是为什么,小弟可能问的太幼稚了,希望各位大虾见谅!!!
[解决办法]
因为 int 的范围比 long 小,会自动向上转型的,不能向下转型。double 比 long 大两级不能向下转型。
自动转型方向可以参见下图:
+-- char
|
double <-- float <-- long <-- int <--+-- short <-- byte