Question

I would like to update specific part of a text file using Java. I would like to be able to scan through the file and select specific lines to be updated, a bit like in a database, for instance given the file:

ID Value
1  100
2  500
4  20

I would like to insert 3 and update 4, e.g.

ID Value
1  100
2  500
3  80
4  1000

Is there a way to achieve this (seemingly) easy task? I know you can append to a file, but I am more interested in a random access

Was it helpful?

Solution

I know you can append to a file, but I am more interested in a random access

You're trying to insert and delete bytes in the middle of a file. You can't do that. File systems simply don't (in general) support that. You can overwrite specific bytes, but you can't insert or delete them.

You could update specific records with random access if your records were fixed-length (in bytes) but it looks like that's not the case.

You could either load the whole file into memory, or read from the original file, writing to a new file with either the old data or the new data as appropriate on a per line basis.

OTHER TIPS

You can do so using Random Access files in java where you can place your current write and read position using available methods. you can explore more here

Load the file into memory, change your value, and then re-write the file

if there's a way to insert into a file without loading it, I haven't heard of it. You have to move the other data out of the way first.

unless you're dealing with huge files, frequently, performance isn't too much of a concern

As said by the previous answers, it's not possible to do that symply using streams. You could try to use properties, that are key, value pairs that can be saved and modified in a text file. For example you can add to a file a new property with the command

setProperty(String key, String value)

This method adds a new property or, if already existing, modifies the value of the property with the choosen key.

Obviously, new properties are added at the end of the file but the lack of ordering is not a problem for performances because the access to the file is made with the getProperty method that calls the Hashtable method put.

See this tutorial for some examples:

http://docs.oracle.com/javase/tutorial/essential/environment/properties.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top