java java中的随机访问文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/199847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 11:23:43  来源:igfitidea点击:

random access file in java

javarandom-access

提问by user21968

I have the following fields:

我有以下字段:

  • Inventory control (16 byte record)
    • Product ID code (int – 4 bytes)
    • Quantity in stock (int – 4 bytes)
    • Price (double – 8 bytes)
  • 库存控制(16 字节记录)
    • 产品 ID 代码(int – 4 字节)
    • 库存数量(int – 4 字节)
    • 价格(双倍 – 8 字节)

How do I create a fixed length random access file using the above lengths? I tried some examples online, but I either get an EOF exception or random address values when I try to access them.

如何使用上述长度创建固定长度的随机访问文件?我在网上尝试了一些示例,但是当我尝试访问它们时,我要么得到 EOF 异常,要么得到随机地址值。

I tried some more examples and couldn't understand the concept very well. I'm trying a project with it and will try to explore more on it.

我尝试了更多示例,但无法很好地理解该概念。我正在尝试一个项目,并将尝试对其进行更多探索。

Here is some example data. There might be holes in the data where No. in stockcould be 23 == 023.

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

          Quantity
ID. No.   In Stock   Price

-------   --------   ------
 1001       476      .35
 1002       240      .56
 1003       517      .27
 1004       284      .75
 1005       165      .25

Thanks for the help.

谢谢您的帮助。

回答by Aaron Maenpaa

java.io.RandomAccessFile is the class you're looking for. Here's an example implementation (you'll probably want to write some unit tests, as I haven't :)

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

回答by Arnav Rao

With recent Java versions, you can manage Random access files using FileChannel. SeekableByteChannel interface define methods which allow you to change the position of the pointer in the destination entity like file which the channel is connected to. FileChannel implements SeekableByteChannel allowing you to manage random access files using channels. Methods size, position, truncate allow you to read and write files randomly.

使用最新的 Java 版本,您可以使用 FileChannel 管理随机访问文件。SeekableByteChannel 接口定义了一些方法,允许您更改指针在目标实体(如通道连接到的文件)中的位置。FileChannel 实现 SeekableByteChannel 允许您使用通道管理随机访问文件。方法大小、位置、截断允许您随机读写文件。

see http://www.zoftino.com/java-random-access-filesfor details and example.

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