日期:2014-05-20  浏览次数:20703 次

一道java程序题
题目是这样的,求解答
编写一个Java应用程序,利用RandomAccessFile类,把几个int型整数(1,2,3,4,5,6,7,8,9,10)写入到一个名字为tom.dat文件中,然后按相反顺序读出这些数据并显示在屏幕上。(注意,一个int型数据占4个字节)

------解决方案--------------------
又见作业贴……
------解决方案--------------------
Java code
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 编写一个Java应用程序,利用RandomAccessFile类,把几个int型整数(1,2,3,4,5,6,7,8,9,10)写入到一个名字为tom.
 * dat文件中,然后按相反顺序读出这些数据并显示在屏幕上。(注意,一个int型数据占4个字节)
 * 
 */
public class Demo
{
    private static final String PATH = "tom.dat";
    private static final int LENGTH = 10;
    private static final int INT_LENGTH = 4;
    
    public static void main(String[] args)
    {
        System.out.println("写进去的数:");
        write();
        System.out.println();
        System.out.println("写好了。。。");
        System.out.println("读出来的数据:");
        read();
    }
    
    private static void write()
    {
        RandomAccessFile raf = null;
        try
        {
            raf = new RandomAccessFile(PATH, "rw");
            for(int i = 0; i < LENGTH; i ++)
            {
                System.out.print(i + "\t");
                raf.writeInt(i);
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                if (null != raf)
                    raf.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
    
    private static void read()
    {
        RandomAccessFile raf = null;
        try
        {
            raf = new RandomAccessFile(PATH, "r");
            for(int i = LENGTH; i > 0; i --)
            {
                raf.seek(INT_LENGTH * (i - 1));
                System.out.print(raf.readInt() + "\t");
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                if (null != raf)
                    raf.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}

------解决方案--------------------
估计是作业题吧。。
试试LS的