0

I have a file which contains lines following the pattern user:pass:role. Right now I'm reading the whole line, then I parse the string with split, modify the values and create a new string, and finally write this new string to the file (deleting the old one).

Instead, I'm looking a way to read and write variable by variable. For example, the file content is:

jake:1234:developer
laura:qwerty:analyst

if I want to change Laura's role to dba, I want to do something like:

while file not empty do
    user = read file till ':'
    if user == "laura" then
        read file till next ':'
        modify "analyst" to "dba"
    else readline

How could I do this?

I have read this question about modifying a file Modifying existing file content in Java, but the answer is to create a new file with the desired values and then delete the old file.

edit

all this arose because if I follow the method I have right now implemented, the new line end up appended to the file. So for instance, in the example above if I change Jake's role to dba, the file will be:

laura:qwerty:analyst
jake:1234:dba

Minor change but I rather keep the order.

Community
  • 1
  • 1

2 Answers2

2

Answers that you have already read are coerent: in general, reading and writing the same file simultaneously is not a good idea.
The common way to do the job is to use a temp file.

Luca Davanzo
  • 21,000
  • 15
  • 120
  • 146
0

you can do this by RandomAccessFile class but because fields sizes is not fixed it is will be hard and complex.

Farvardin
  • 5,336
  • 5
  • 33
  • 54