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)
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.
Here is some example data. There might be holes in the data where No. in stock
could be 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
Thanks for the help.
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 :)
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.
see http://www.zoftino.com/java-random-access-files for details and example.