02-22-2010 09:39 AM
I am using java.io.DataInputStream and java.io.DataOutputStream to read/write files. However i need to modify a file now, which will require me to insert information into the middle of a previous file.
I don't see any methods of doing so in the DataOutputStream. Is there a way to 'insert' into a middle of a file easily on bb, or do i have to do custom -copy/overwrite/append stuff?
Solved! Go to Solution.
02-22-2010 03:48 PM
If it is a file you can call FileConnection.openOutputStream(long byteOffset). Otherwise you need to make a custom class.
02-22-2010 04:18 PM
You can seek into the file, but writing at that position will clobber what's there. This desired non-destructive file insert is normally not something that is supported usually elsewhere as well.
02-22-2010 04:18 PM - edited 02-22-2010 04:21 PM
Yeah, that wasn't what i needed exactly but after some more designing i came up with another method of doing it. The problem now is that i need to be able to seek within the file forward and backwards. I am using FileConnector and DataInputStream, i can skip bytes to seek forward...but there doesn't seem to be any way to seek backwards. Is there another class i can use for this? Opening and closing a file a few times just so that i can seek from the beginning is not a good idea....:/
Yeah, i know that non-destructive insert isn't usually support elsewhere either but it would be useful...though inherently slow... A/w see the above comments that i made, any ideas how to seek backwards? The DataINputStream doesn't allow that....
02-22-2010 04:30 PM
You could do it yourself, but it would be more difficult. You could buffer the file data yourself, but not knowing necessarily where to buffer to or how big to buffer could lead to reconsidering just reopening streams. Depends on your situation.
02-22-2010 04:35 PM
Yeah, thats my plan. I'll just read the data into a buffer and parse that....the sizes are predictable so shouldn't be a big perf hit. Too bad that something this basic is missing....
02-22-2010 04:37 PM
I don't think what you suggest is possible with any of the standard APIs OpenOutputStream (int offset) would overwrite, not replace (to the best of my understanding of these things). I wish you luck, but I don't believe you'll get out of this without reading the whole file into a local source first. On that note, you'll have to be pretty picky about what structure you use if you're manipulating large files. Using byte  would be efficient (relatively), but you wouldn't be able to insert mid-file very easily. Vectors are great for inserting, but everything needs to be explicitly parsed, and they take up more space and processing power than arrays.
02-22-2010 07:28 PM - edited 02-22-2010 07:28 PM
Yea, as others have said, the openOutputStream is destructive. Sorry if that didn't help.