Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify a .txt file in Java

Tags:

java

I have a text file that I want to edit using Java. It has many thousands of lines. I basically want to iterate through the lines and change/edit/delete some text. This will need to happen quite often.

From the solutions I saw on other sites, the general approach seems to be:

  • Open the existing file using a BufferedReader
  • Read each line, make modifications to each line, and add it to a StringBuilder
  • Once all the text has been read and modified, write the contents of the StringBuilder to a new file
  • Replace the old file with the new file

This solution seems slightly "hacky" to me, especially if I have thousands of lines in my text file.

Anybody know of a better solution?

like image 525
Zakir Hemraj Avatar asked May 04 '09 21:05

Zakir Hemraj


People also ask

How do I edit an existing file in Java?

open a temporary file in writing mode at the same time, and for each line, read it, modify if necessary, then write into the temporary file. At the end, delete the original and rename the temporary file.

Can you edit a txt file?

Windows Text Editor for Conveniently Editing Text Documents or TXT Files. While you could edit text files with good old Windows Notepad, or any other free text editor, EditPad Pro is a powerful text editor that makes the job far more comfortable.

How do you replace a character in a file in Java?

The replaceAll() method of the String class accepts two strings representing a regular expression and a replacement String and replaces the matched values with given String. Read the contents of a file to a String.


1 Answers

I haven't done this in Java recently, but writing an entire file into memory seems like a bad idea.

The best idea that I can come up with is open a temporary file in writing mode at the same time, and for each line, read it, modify if necessary, then write into the temporary file. At the end, delete the original and rename the temporary file.

If you have modify permissions on the file system, you probably also have deleting and renaming permissions.

like image 185
Andrei Krotkov Avatar answered Sep 19 '22 15:09

Andrei Krotkov