I've created a file using java.io.File
, FileInputStream & FileOutputStream
. Suppose that I want to change the value of some bytes in the file (for instance from the byte 15 to 35) without changing the size of the file. I've tried creating a RandomAccessFile
object and then use RandomAccessFile.seek
to move to byte number 15, writing my new bytes and then closing the file. The file has changed its size. What's wrong with this approach, and how can this be done successfully?
Asked
Active
Viewed 1,207 times
4
-
1Yes, please show us a snippit of the code you are using. – jjnguy Nov 19 '10 at 15:37
-
2I assume you are not trying to use FileOutputStream AND RandomAccessFile at the same time. – Peter Lawrey Nov 19 '10 at 15:38
-
If you are using RandomAccessFile alone, the only way to change it is size is to use setLength(). Unless you are using that, the size shouldn't change. – Peter Lawrey Nov 19 '10 at 15:40
-
@Peter, if you write past the end, the size will increase also. – Marcus Adams Nov 19 '10 at 15:42
-
@Peter You was assuming wrong. Thanks to u I ve fixed. Thanks a lot. – Blackbelt Nov 19 '10 at 16:21
-
If you have to play a lot with file, Take a look a Apache Common IO: http://commons.apache.org/io/ – Aerosteak Nov 21 '10 at 03:07
1 Answers
4
Are you sure you are writing a byte to the RandomAccessFile? If you are calling the method:
file.write(35);
Then it is actually writing 35
as an int
which is 4 bytes. If you want to write a single byte try:
file.writeByte(35);

DaveJohnston
- 10,031
- 10
- 54
- 83