This example code teaches you how to Write to a File in Java without overwriting.
Learn how to Write to a File in Java without overwriting in your Java program
This tutorial teaches you how to write to a file in Java without overwriting the existing content. This type of application is useful in writing the application log data into a file. In this this we have a "log.txt" file which already contains the data and our program will write to this file without overwriting the content of "log.txt" file. Next time if you write something to this file then the content will be appended to it.
In this program we are using the FileWriter class of the java.io package.
Our examples code appends a line to the log.txt file when executed. Following is the code which appends the line to the log.txt file:
out.write("Line Added on: " + new java.util.Date()+"\n");
Our program uses the Java API for this purpose. The object of FileWriter is created using the following code:
FileWriter fstream = new FileWriter("log.txt",true);
Here is the syntax of the FileWriter class:
FileWriter(File file, boolean append)
The FileWriter class takes two parameters:
1. File file: the name of the file to be opened.
2. boolean append: If this parameter is true then the data is written to the end of the file. In other words it appends the data at the end of file.
So, if in your program you have a requirement to append the data into file then you should pass the true as parameter.
Here is the complete example code of the program:
import java.io.*; class WriteToFileWithoutOverwriting { public static void main(String args[]) { try{ FileWriter fstream = new FileWriter("log.txt",true); BufferedWriter out = new BufferedWriter(fstream); out.write("Line Added on: " + new java.util.Date()+"\n"); out.close(); }catch (Exception e){ System.err.println("Error while writing to file: " + e.getMessage()); } } }
To compile the program type following line on command prompt:
javac WriteToFileWithoutOverwriting.java
To execute the program type following on the command prompt:
java WriteToFileWithoutOverwriting
In the above program you have learned how to write code to to append the content in a text file through your Java program. Program explained here writes the content to a file (text file) without overwriting the content of the file. This type of program is very useful in writing log information to a file.