2

In my project, we are writing a file using DataOutputStream. We are writing different data types like short, byte, int and long and we are using respective methods in DataOutputStream like writeShort(), writeByte() etc.

Now, I want to edit one record in this file at a particular offset. I know the offset from which that record starts but I am not sure what is the right approach of writing to the file because only method in DataOutputStream supporting offset is the one which takes byte[].

I want to write the whole record which is a combination of different data types as mentioned above.

Can someone please tell me what is the correct approach for this?

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
Bagira
  • 2,149
  • 4
  • 26
  • 55
  • Are the records fixed size? – Kayaman Nov 14 '16 at 07:47
  • No, records have different size. – Bagira Nov 14 '16 at 07:47
  • 3
    "only method in DataoutputStream supporting offset is the one which takes byte[]" => The offset in method [`DataOutputStream#write(byte[], int, int)`](https://docs.oracle.com/javase/8/docs/api/java/io/DataOutputStream.html#write-byte:A-int-int-) means the offset in the _data_ you are writing, not some position in the _stream_. – Seelenvirtuose Nov 14 '16 at 07:49
  • Additionally: It's the nature of a stream to not provide _random access_ by using offsets or similar. See Nicolas' answer for an alternative. – Seelenvirtuose Nov 14 '16 at 07:55

1 Answers1

2

In your case, you should use RandomAccessFile in order to read and/or write some content in a file at a given location thanks to its method seek(long pos).

For example:

try (RandomAccessFile raf = new RandomAccessFile(filePath, "rw")) {
    raf.seek(offset);
    // do something here
}

NB: The methods writeShort(), writeByte() etc. and their read counterparts are directly available from the class RandomAccessFile so using it alone is enough.

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
  • Of course if the records aren't fixed size, there's a chance of corrupting the file if you just overwrite content in the middle. – Kayaman Nov 14 '16 at 11:13