我有以下领域:

  • 库存控制(16字节的记录)
    • 产品编码(int–4字节)
    • 库存数量(int–4字节)
    • 价格(双8字节)

我如何创建一个固定长度的随机存取文件使用上述长度?我尝试了一些例子,但我要么得到EOF异常或随机地址的价值观时,我尝试要对它们进行访问。

我尝试一些更多的例子并不能理解这个概念非常好。我想一个项目,它将努力探索更多。

这里是一些例子的数据。有可能是在孔的数据在哪里 No. in stock 可能是 23 == 023.

          Quantity
ID. No.   In Stock   Price

-------   --------   ------
 1001       476      $28.35
 1002       240      $32.56
 1003       517      $51.27
 1004       284      $23.75
 1005       165      $32.25

谢谢你的帮助。

有帮助吗?

解决方案

java。io.RandomAccessFile类是你要找的。这是一个实例执行情况(你可能会想要写入一些单元的测试,我没有:)

package test;

import java.io.IOException;
import java.io.RandomAccessFile;

public class Raf {
    private static class Record{
        private final double price;
        private final int id;
        private final int stock;

        public Record(int id, int stock, double price){
            this.id = id;
            this.stock = stock;
            this.price = price;
        }

        public void pack(int n, int offset, byte[] array){
            array[offset + 0] = (byte)(n & 0xff);
            array[offset + 1] = (byte)((n >> 8) & 0xff);
            array[offset + 2] = (byte)((n >> 16) & 0xff);
            array[offset + 3] = (byte)((n >> 24) & 0xff);
        }

        public void pack(double n, int offset, byte[] array){
            long bytes = Double.doubleToRawLongBits(n);
            pack((int) (bytes & 0xffffffff), offset, array);
            pack((int) ((bytes >> 32) & 0xffffffff), offset + 4, array);
        }

        public byte[] getBytes() {
            byte[] record = new byte[16];
            pack(id, 0, record);
            pack(stock, 4, record);
            pack(price, 8, record);
            return record;
        }
    }

    private static final int RECORD_SIZE = 16;
    private static final int N_RECORDS = 1024;

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        RandomAccessFile raf = new RandomAccessFile(args[0], "rw");
        try{
            raf.seek(RECORD_SIZE * N_RECORDS);

            raf.seek(0);

            raf.write(new Record(1001, 476, 28.35).getBytes());
            raf.write(new Record(1002, 240, 32.56).getBytes());
        } finally {
            raf.close();
        }
    }
}

其他提示

最近Java版本,可以管理随机存取文件,使用FileChannel.SeekableByteChannel口定义方法能让你改变位置的指的目的实体等文件,该文件的通道连接。FileChannel实现SeekableByteChannel让你来管理随机存取文件使用的渠道。方法的大小、位置、截断让你读和写的文件。

看看 http://www.zoftino.com/java-random-access-files 对于细节和实例。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top