java中的随机访问文件 [英] random access file in java
问题描述
我有以下字段:
- 库存控制(16字节记录)
- 产品ID代码(int - 4字节)
- 库存数量(整数 - 4字节)
- 价格(双 - 8字节)
如何使用以下方法创建固定长度的随机访问文件以上长度?我在网上尝试了一些例子,但是当我尝试访问它们时,我得到了一个EOF异常或随机地址值。
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.
我尝试了一些更多的例子而无法理解概念非常好。我正在尝试一个项目,并将尝试探索更多。
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.
这是一些示例数据。数据中可能存在漏洞
否。有货
可能23 == 023
。Here is some example data. There might be holes in the data where
No. in stock
could be23 == 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是您正在寻找的类。这是一个示例实现(您可能想要编写一些单元测试,因为我没有:)
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 :)
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中的随机访问文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!