Java中的随机访问文件

4
我有以下字段:
  • 库存控制(16字节记录)
    • 产品ID代码(int - 4字节)
    • 库存数量(int - 4字节)
    • 价格(double - 8字节)
如何使用上述长度创建固定长度的随机访问文件?我尝试了一些在线示例,但当我尝试访问它们时,要么出现EOF异常,要么出现随机地址值。
我尝试了更多的示例,但无法很好地理解这个概念。我正在尝试一个与此相关的项目,并将尝试进一步探索它。
这里是一些示例数据。数据中可能会有空洞,其中库存数量可能为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

感谢您的帮助。
2个回答

10

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();
        }
    }
}

0

在最近的Java版本中,您可以使用FileChannel管理随机访问文件。SeekableByteChannel接口定义了一些方法,允许您更改指针在目标实体(如通道所连接的文件)中的位置。FileChannel实现了SeekableByteChannel,使您能够使用通道管理随机访问文件。size、position和truncate方法允许您随机读写文件。

有关详细信息和示例,请参见http://www.zoftino.com/java-random-access-files


链接无法使用 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接