2

I want to write a ~20000 bytes to a replace the same number of bytes of file at offset OFFSET using a BufferedOutputStream. I try to do this with the following code:

headerOffset = 12000;
headerSize = 20000;
byte[] ba = new byte[20];
FileOutputStream os;
BufferedOutputStream bos;
try {
  os = new FileOutputStream('file.dat');
  bos = new BufferedOutputStream(os);
  bos.write(ba, headerOffset, headerSize);
  os.flush();
} catch (IOException e) { e.printStackTrace(); }

However, this results in the 'file.dat' being overwritten by the contents of ba overwriting the entire file and leaving it only as big as ba. What am I doing wrong?

DannyClay
  • 260
  • 3
  • 11
  • 1
    Short answer; you don't. http://docs.oracle.com/javase/tutorial/essential/io/rafs.html with NIO or `RandomAccessFile` – Brian Roach May 08 '13 at 01:49
  • 1
    Use `RandomAccessFile`. See ***[this](http://stackoverflow.com/questions/5786697/how-to-write-content-in-a-specific-position-in-a-file)*** post – Extreme Coders May 08 '13 at 01:50
  • Thanks for your comments. I originally had used `RandomAccessFile` but felt it was too slow. Perhaps I was doing something wrong. Anyway, I'm going to revisit it and try to improve what I was trying to do earlier. – DannyClay May 08 '13 at 02:05

0 Answers0