首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

关于RandomAccessFile中的seek(long pos)方法?解决思路

2012-02-01 
关于RandomAccessFile中的seek(long pos)方法?importjava.io.*publicclassReadRandom{publicstaticString

关于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

热点排行