How to replace/overwrite a line in a file in Java?

Posted 19 January 2013 - 09:29 AM

I have a program which allows the user to search a record from a file by typing the name. Then the record will appear in the text boxes provided, so that the user can edit them. However, i can read the file, but i dont know how to edit or replace the line after the user edits the textboxes.

Replies To: How to replace/overwrite a line in a file in Java?

Re: How to replace/overwrite a line in a file in Java?

Posted 19 January 2013 - 09:46 AM

It doesn't matter what language you are using...
Text files cannot {easily} replace just one line {of changing length}, nor can you insert a line {of different length} in the middle of a text file. The most you can do is append to a text file. To replace or insert a line you need to read in the file, do your manipulations in memory, then write out the entire file.

I have a CodeSnippet where I save an array on such a file. It is then possible to change an array element on that file.
UI cannot access the CodeSnippet section of the forum right now so I'll repost the code

Re: How to replace/overwrite a line in a file in Java?

Posted 19 January 2013 - 03:18 PM

tlhIn`toq, on 19 January 2013 - 09:46 AM, said:

It doesn't matter what language you are using...
Text files cannot {easily} replace just one line {of changing length}, nor can you insert a line {of different length} in the middle of a text file. The most you can do is append to a text file. To replace or insert a line you need to read in the file, do your manipulations in memory, then write out the entire file.

Do you know where i can find any existing code that i can modify please?

Re: How to replace/overwrite a line in a file in Java?

Posted 21 January 2013 - 05:03 AM

I have managed to read the file, create a temp file, and then replace the first word that i found in the search textfield. As i mentioned above, i have splitted each line and iam able to get the inputs from the file to each texfields. Now i would like to edit textfield1, textfield2, textfield3, textfield4 on the line that was found in the search.

For instance, in the original file i have the following code:

Bren........Ramal.......Valera.......Ruiz

Now whenever i type Bren in the search textfield, then iam able to get Bren in textfield1, Ramal in textfield2, Valera in textfield3, Ruiz in textfield4.

So, For example, how will i tell the program to replace Bren to Bren1, Ramal to Ramal1, Valera to Valera1, Ruiz to Ruiz1 at once.

Re: How to replace/overwrite a line in a file in Java?

Posted 24 January 2013 - 12:40 PM

I have managed to replace the items that i want from all 4 textfields. I have created a temp file but whenever i write the changes to the temp file and then to the original file, it deletes the other contents and only stores that line that i changed.