• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Another Question?

 
long lingyu
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry, I find that when I used the write(byte[]) method of RandomAccessFile,it only write the byte[] length. So if the data's length is less than the field length, it will be wrong! How can handle this?
 
George Marinkovich
Ranch Hand
Posts: 619
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Long,
Originally posted by long lingyu:
Sorry, I find that when I used the write(byte[]) method of RandomAccessFile,it only write the byte[] length. So if the data's length is less than the field length, it will be wrong! How can handle this?

Here are two ideas:
Well, you know what the field length is supposed to be so you can declare a byte[] of the correct size for the field. Assuming the field value is in a string you can use String.getBytes(String charsetName) to get a byte array (using the proper data encoding). Then you could use System.arrayCopy to copy the second array into the first array and write the first array.
Or, you could get a byte[] from the field value using String.getBytes(String charsetName) and write that array. Then create a second array that is sized to be ((field length) - (length of first array) + 1) bytes and write that array to the database file.
It's up to you to decide whether you want to do an arrayCopy or two writes. Of course, there may be other, better, ways to do this.
[ March 08, 2004: Message edited by: George Marinkovich ]
 
long lingyu
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you
 
long lingyu
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have tested. There is a question: If the length of the two array is not equaled, it may throw some exception,how can I resolve the problem?
 
George Marinkovich
Ranch Hand
Posts: 619
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Long,
Originally posted by long lingyu:
I have tested. There is a question: If the length of the two array is not equaled, it may throw some exception,how can I resolve the problem?

I guess you're talking about the solution using the arraycopy:

There's only room for 32 characters so if you try to store a field value having more than 32 characters you only save the first 32.
You could instead allow an IndexOutOfBoundsException to be thrown when fieldValue.length exceeds the fieldBuffer:
 
long lingyu
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are a nice guy.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic