File Update In Java
We are examining how to update txt – Csv and JSON files in Java with examples.
Java File Update – Txt
In java file update, we can replace any word in a txt file at its first occurrence by using the replace() method from the String methods:
Example:
The same goal can also be achieved by creating a method once and calling it as many time as we want:
Example:
Correspondingly, We can Also replace all the same words in a txt file by matching it with any specific String, using the replaceAll() method from Java Strings.
Example:
In the similar way, we can also create a method to match a string and replace all the corresponding words from the file.
Here we have created a method named replace_word_multiple_times() to replace multiple words in a txt file:
Example:
Java File Update – CSV
We can also update the content of the .csv file as shown in the examples below.
To modify a word at its first occurrence follow the example below:
Example:
Correspondingly, we can also modify all the same words in a .csv file after matching them all:
Example:
Now, to do this work more efficiently, let’s make methods named replace_word_multiple_times() and replace_word_single_time() as shown below:
Example:
Java File Update – JSON
We can also update the data of the .json file as shown in the examples below.
To modify a word at its first occurrence follow the example below:
Example:
Correspondingly, we can also modify multiple words in a .json file after matching them and then replacing them using replaceAll() method :
Example:
Here, we have create two different methods – One for updating first match word occurrence and second for all match words in a JSON file:
Example:
Now you know how to update Txt, JSON and Csv files in Java.