Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to resolve Data file

 
weibin wu
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry for asking so simply question.But I cann't sure my mind about the data file. Can I use these code to resolve file?And is there any other ways to resolve it without FileChannel?
4 byte numeric, magic cookie value identifies this as a data file
RandomAccessFile file = new RandomAccessFile("f:\\db-2x2.db", "rw");
FileChannel fc = file.getChannel();
MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size());
ByteBuffer bb = mbb.get(bytes, 0, 4);
int magicCookie = bb.getInt();
 
Matthew Blaise
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure why you are using a FileChannel. I'm not too familiar with them so please let me know if there is some advantage to your method.
I'm just using the RandomAccessFile.
e.g.
RandomAccessFile raf = new RandomAccessFile("dbfile", "r");
int magicCookie = raf.readInt();
Anything wrong with this?
Blaise
 
weibin wu
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for your reply.But I wonder how you can sure getInt() contains 4 byte.Here is the require
Start of file
4 byte numeric, magic cookie value identifies this as a data file
4 byte numeric, offset to start of record zero
2 byte numeric, number of fields in each record
Can readInt() get correctly number?
RandomAccessFile file = new RandomAccessFile("f:\\db-2x2.db", "rw");
byte[] bytes = new byte[100];
file.read(bytes, 0, 4);
Is it a correctly method to get 4 byte?If so I don't know how convert bytes
into int?Can you give me some advice?
 
Matthew Blaise
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"numeric" is not defined exactly, so I tried to narrow the specification in my documentation:

The primitive type "int" in java is defined as a 4 byte signed integer. The "readInt()" declared by the DataInputStream interface and defined by RandomAccessFile should read the next four bytes from your file and put them in an int to return to you. So, yes, raf.readInt() should always work.
If you wanted to construct an int from 4 bytes you'll have to use some shifts and masks. Make sure you conform to one byte order, "big-endian".

Does this help?
Blaise
 
Matthew Blaise
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One note though...readInt() would not work and throw an exception if it reaches end-of-file before reading the fourth byte.
Blaise
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic