how-to-append-text-to-an-existing-file-in-java?

While utilizing Java, we may encounter circumstances where it is necessary to supplement some text or information to an already existing file, such as modifying transaction records, refreshing the content of a blog, or altering the content of a file. Java offers several methods to add text or binary data to a pre-existing file.

In this article, we will explore various techniques to append text to an existing file in Java.

Contents Overview:

Ways to Append Text to an Existing File in Java

Java offers a variety of methods to add text to an already existing file. Below are some of these methods:

Technique 1: Append Text to an Existing File using java.io Package

We can utilize the java.io package for appending text to an existing file in Java. It provides several classes such as FileWriter, BufferedWriter, and PrintWriter for appending text to an existing file.

1.1 Employing FileWriter

The FileWriter class permits writing characters to a file. By specifying true as the second argument in its constructor, we activate append mode.

Example:

example.txt – Prior to Appending:

Learn Java File Handling

Code:

Java

Code Copied!

var isMobile = window.innerWidth “);

editor16165.setValue(decodedContent); // Set the default text editor16165.clearSelection();

editor16165.setOptions({ maxLines: Infinity });

function decodeHTML16165(input) { var doc = new DOMParser().parseFromString(input, ‘text/html’); return doc.documentElement.textContent; }

function copyCodeToClipboard16165() { const code = editor16165.getValue(); navigator.clipboard.writeText(code).then(() => { jQuery(“.maineditor16165 .copymessage”).show(); setTimeout(function() { jQuery(“.maineditor16165 .copymessage”).hide(); }, 2000); }).catch(err => { console.error(“Error copying code: “, err); }); }

function runCode16165() { var code = editor16165.getSession().getValue();

jQuery(“#runBtn16165 i.run-code”).show(); jQuery(“.output-tab”).click();

jQuery.ajax({ url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”, type: “post”, data: { language: “java”, code: code, cmd_line_args: “”, variablenames: “”, action:”compilerajax” }, success: function(response) { var myArray = response.split(“~”); var data = myArray[1];

jQuery(“.output16165”).html(“

"+data+"

“); jQuery(“.maineditor16165 .code-editor-output”).show(); jQuery(“#runBtn16165 i.run-code”).hide(); } }) }

function closeoutput16165() { jQuery(“.maineditor16165 .code-editor-output”).hide(); }

// Attach event listeners to the buttons document.getElementById(“copyBtn16165”).addEventListener(“click”, copyCodeToClipboard16165); document.getElementById(“runBtn16165”).addEventListener(“click”, runCode16165); document.getElementById(“closeoutputBtn16165”).addEventListener(“click”, closeoutput16165);

Output:

“`html
class=”aligncenter size-full”>Using FileWriter Output

Description: In the preceding code snippet, we utilized

  • new FileWriter(filePath, true): The parameter true activates append mode.
  • .write(): This function appends new content at the file’s conclusion.

example.txt – Subsequent to Appending:

Learn Java File Management 

Appending text utilizing FileWriter.

1.2 Employing BufferedWriter

BufferedWriter belongs to the java.io package and is designed for effectively writing textual data to a file. It is typically favored over FileWriter as it buffers characters, decreasing the number of write operations, thus enhancing efficiency.

Illustration:

example.txt – Prior to Appending:

Java Append File Sample  
Discover how to effectively include text in a file using Java.

Code:

Java

Code Duplicated!

var isMobile = window.innerWidth “);

editor46522.setValue(decodedContent); // Set the default text
editor46522.clearSelection();

editor46522.setOptions({
maxLines: Infinity
});

function decodeHTML46522(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}

// Function to copy code to clipboard
function copyCodeToClipboard46522() {
const code = editor46522.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert(“Code copied to clipboard!”);

jQuery(“.maineditor46522 .copymessage”).show();
setTimeout(function() {
jQuery(“.maineditor46522 .copymessage”).hide();
}, 2000);
}).catch(err => {
console.error(“Error copying code: “, err);
});
}

function runCode46522() {

var code = editor46522.getSession().getValue();

jQuery(“#runBtn46522 i.run-code”).show();
jQuery(“.output-tab”).click();

jQuery.ajax({
url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”,
type: “post”,

data: {
language: “java”,
code: code,
cmd_line_args: “”,
variablenames: “”,
action:”compilerajax”
},
success: function(response) {
var myArray = response.split(“~”);
var data = myArray[1];

jQuery(“.output46522”).html(“

"+data+"");
									jQuery(".maineditor46522 .code-editor-output").show();
									jQuery("#runBtn46522 i.run-code").hide();
									
								}
							})
}

function closeoutput46522() {	
	var code = editor46522.getSession().getValue();
	jQuery(".maineditor46522 .code-editor-output").hide();
}

// Attach event listeners to the buttons
document.getElementById("copyBtn46522").addEventListener("click", copyCodeToClipboard46522);
document.getElementById("runBtn46522").addEventListener("click", runCode46522);
document.getElementById("closeoutputBtn46522").addEventListener("click", closeoutput46522);


Result:

Using BufferedWriter Output

Description: Within the code above, BufferedWriter enhances efficiency by minimizing the frequency of direct write actions to the file.

example.txt – Following Appending:

Java Append File Sample  
Discover how to effectively include text in a file using Java.  
Appending text utilizing BufferedWriter.

1.3 Utilizing PrintWriter

PrintWriter serves as another beneficial class within the java.io package that facilitates the writing of formatted text into a file. It offers functions such as println(), printf(), and print(), simplifying the process of writing text in an already existing file.

Illustration:

example.txt – Prior to Appending:

Appending Data in Java Files

Code:

Java

Code Duplicated!

var isMobile = window.innerWidth ");

editor18667.setValue(decodedContent); // Initialize with default text
editor18667.clearSelection();

editor18667.setOptions({
maxLines: Infinity
});

function decodeHTML18667(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}

// Function to duplicate code to clipboard
function copyCodeToClipboard18667() {
const code = editor18667.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code duplicated to clipboard!");

jQuery(".maineditor18667 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor18667 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error duplicating code: ", err);
});
}

function runCode18667() {

var code = editor18667.getSession().getValue();

jQuery("#runBtn18667 i.run-code").show();
jQuery(".output-tab").click();

jQuery.ajax({
url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php",
type: "post",

data: {
language: "java",
code: code,
cmd_line_args: "",
variablenames: "",
action:"compilerajax"
},
success: function(response) {
var myArray = response.split("~");
var data = myArray[1];

jQuery(".output18667").html("

"+data+"");
									jQuery(".maineditor18667 .code-editor-output").show();
									jQuery("#runBtn18667 i.run-code").hide();
									
								}
							})
					

						}
						
						
		function closeoutput18667() {	
		var code = editor18667.getSession().getValue();
		jQuery(".maineditor18667 .code-editor-output").hide();
		}

    // Attach event listeners to the buttons
    document.getElementById("copyBtn18667").addEventListener("click", copyCodeToClipboard18667);
    document.getElementById("runBtn18667").addEventListener("click", runCode18667);
    document.getElementById("closeoutputBtn18667").addEventListener("click", closeoutput18667);
 
    



Output:

Using PrintWriter Output

Clarification:

  • PrintWriter enables you to write formatted text to a file.
  • .println() introduces a new line following each segment of content.

example.txt – Following Appending:

Appending Data in Java Files  

Adding text using PrintWriter.

Method 2: Utilizing FileOutputStream for Appending

FileOutputStream is a component of the java.io package and is designed for writing binary or text data to a file. When engaged in append mode, it guarantees that new data is incorporated at the file’s end without erasing the pre-existing content.

Illustration:

example.txt – Preceding Appending:

Java File Append Mode Clarified

Code:

Java

Code Duplicated!

var isMobile = window.innerWidth “);

editor17980.setValue(decodedContent); // Initialize with default text
editor17980.clearSelection();

editor17980.setOptions({
maxLines: Infinity
});

function decodeHTML17980(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}

// Function to duplicate code to clipboard
function copyCodeToClipboard17980() {
const code = editor17980.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert(“Code duplicated to clipboard!”);

jQuery(“.maineditor17980 .copymessage”).show();
setTimeout(function() {
jQuery(“.maineditor17980 .copymessage”).hide();
}, 2000);
}).catch(err => {
console.error(“Error duplicating code: “, err);
});
}

function runCode17980()
“““javascript
{

var script = editor17980.getSession().getValue();

jQuery(“#runBtn17980 i.run-code”).show();
jQuery(“.output-tab”).click();

jQuery.ajax({
url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”,
type: “post”,

data: {
language: “java”,
code: script,
cmd_line_args: “”,
variablenames: “”,
action:”compilerajax”
},
success: function(response) {
var myArray = response.split(“~”);
var outputData = myArray[1];

jQuery(“.output17980”).html(“

"+outputData+"");
									jQuery(".maineditor17980 .code-editor-output").show();
									jQuery("#runBtn17980 i.run-code").hide();
									
								}
							})
					

						}
						
						
		function closeoutput17980() {	
		var script = editor17980.getSession().getValue();
		jQuery(".maineditor17980 .code-editor-output").hide();
		}

    // Add event listeners to the buttons
    document.getElementById("copyBtn17980").addEventListener("click", copyCodeToClipboard17980);
    document.getElementById("runBtn17980").addEventListener("click", runCode17980);
    document.getElementById("closeoutputBtn17980").addEventListener("click", closeoutput17980);
 
    



Result:

Using FileOutputStream for Appending Output

Clarification:

  • .write(data.getBytes()) transforms the text into byte format.
  • true as an argument permits append mode.

example.txt – Post Appending:

Java File Append Mode Explained 

Incorporating text using FileOutputStream.

Method 3: Utilizing java.nio.file for Appending

The java.nio.file package simplifies file management, making it more efficient. You can leverage the Files.write() function with StandardOpenOption.APPEND to insert text into an existing file without overwriting its existing content.

Instance:

example.txt – Prior to Appending:

Effective File Management in Java

Code:

Java

Code Copied!

var isMobile = window.innerWidth “);

editor88525.setValue(decodedContent); // Establish the default text
editor88525.clearSelection();

editor88525.setOptions({
maxLines: Infinity
});

function decodeHTML88525(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}

// Function to copy code to clipboard
function copyCodeToClipboard88525() {
const code = editor88525.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert(“Code copied to clipboard!”);

jQuery(“.maineditor88525 .copymessage”).show();
setTimeout(function() {
jQuery(“.maineditor88525 .copymessage”).hide();
}, 2000);
}).catch(err => {
console.error(“Error copying code: “, err);
});
}

function runCode88525() {

var script = editor88525.getSession().getValue();

jQuery(“#runBtn88525 i.run-code”).show();
jQuery(“.output-tab”).click();

jQuery.ajax({
url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”,
type: “post”,

data: {
language: “java”,
code: script,
cmd_line_args: “”,
variablenames: “”,
action:”compilerajax”
},
success: function(response) {
var myArray = response.split(“~”);
var outputData = myArray[1];

jQuery(“.output88525”).html(“

"+outputData+"");
									jQuery(".maineditor88525 .code-editor-output").show();
									jQuery("#runBtn88525 i.run-code").hide();
									
								}
							})
					

						}
						
						
		function closeoutput88525() {	
		var script = editor88525.getSession().getValue();
		jQuery(".maineditor88525 .code-editor-output").hide();
		}

    // Attach event listeners to the buttons
    document.getElementById("copyBtn88525").addEventListener("click", copyCodeToClipboard88525);
    document.getElementById("runBtn88525").addEventListener("click", runCode88525);
    document.getElementById("closeoutputBtn88525").addEventListener("click", closeoutput88525);
 
    



Result:

Using java.nio.file for Appending Output

Clarification:

  • Files.write() attaches text to a file in a more straightforward and contemporary manner.
  • StandardOpenOption.APPEND ensures that information is added instead of overwritten.

example.txt “`– Following Append Operation:

Efficient File Management in Java 

Adding text via java.nio.file.

Method 4: Utilizing External Libraries

It is also possible to add text to a file in Java by employing Guava and Apache Commons IO, which generally enhances file management while also boosting performance.

4.1 Utilizing Guava

Google Guava is a robust external library for Java file management. The Files.append() method from the Guava’s com.google.common.io.Files class offers a simple approach to add text to an existing file.

Example:

example.txt – Prior to Append:

Employing Guava for Java File Functions

Code:

Java

Code Copied!

var isMobile = window.innerWidth “);

editor44177.setValue(decodedContent); // Set the default text
editor44177.clearSelection();

editor44177.setOptions({
maxLines: Infinity
});

function decodeHTML44177(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}

// Function to copy code to clipboard
function copyCodeToClipboard44177() {
const code = editor44177.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
jQuery(“.maineditor44177 .copymessage”).show();
setTimeout(function() {
jQuery(“.maineditor44177 .copymessage”).hide();
}, 2000);
}).catch(err => {
console.error(“Error copying code: “, err);
});
}

function runCode44177() {
var code = editor44177.getSession().getValue();

jQuery(“#runBtn44177 i.run-code”).show();
jQuery(“.output-tab”).click();

jQuery.ajax({
url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”,
type: “post”,

data: {
language: “java”,
code: code,
cmd_line_args: “”,
variablenames: “”,
action:”compilerajax”
},
success: function(response) {
var myArray = response.split(“~”);
var data = myArray[1];

jQuery(“.output44177”).html(“

"+data+"");
									jQuery(".maineditor44177 .code-editor-output").show();
									jQuery("#runBtn44177 i.run-code").hide();
									
								}
							})
					

						}
						
						
function closeoutput44177() {	
		var code = editor44177.getSession().getValue();
		jQuery(".maineditor44177 .code-editor-output").hide();
	}

// Attach event listeners to the buttons
document.getElementById("copyBtn44177").addEventListener("click", copyCodeToClipboard44177);
document.getElementById("runBtn44177").addEventListener("click", runCode44177);
document.getElementById("closeoutputBtn44177").addEventListener("click", closeoutput44177);
 


Output:

Using Guava Output

example.txt – Following Append Operation:

Employing Guava for Java File Functions 

Adding text via Guava.

Note: Please include the following dependency in your Maven project in order to execute the above code:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>32.0.0-jre</version>
</dependency>

4.2 Utilizing Apache Commons IO FileUtils

Apache Commons IO is a well-known external library that facilitates file management in Java. The FileUtils.writeStringToFile() method allows easy appending of text to an existing file.

Example:

example.txt – Prior to Append:

Apache Commons IO for Java Files 

Code:

Java

Code Copied!

var```javascript
isMobile = window.innerWidth ");

editor56893.setValue(decodedContent); // Set the initial text
editor56893.clearSelection();

editor56893.setOptions({
maxLines: Infinity
});

function decodeHTML56893(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}

// Function to duplicate code to clipboard
function copyCodeToClipboard56893() {
const code = editor56893.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code copied to clipboard!");

jQuery(".maineditor56893 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor56893 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error copying code: ", err);
});
}

function runCode56893() {
var code = editor56893.getSession().getValue();

jQuery("#runBtn56893 i.run-code").show();
jQuery(".output-tab").click();

jQuery.ajax({
url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php",
type: "post",
data: {
language: "java",
code: code,
cmd_line_args: "",
variablenames: "",
action: "compilerajax"
},
success: function(response) {
var myArray = response.split("~");
var data = myArray[1];

jQuery(".output56893").html("

"+data+"");
            jQuery(".maineditor56893 .code-editor-output").show();
            jQuery("#runBtn56893 i.run-code").hide();
        }
    });
}
						
function closeOutput56893() {	
    var code = editor56893.getSession().getValue();
    jQuery(".maineditor56893 .code-editor-output").hide();
}

// Connect event handlers to the buttons
document.getElementById("copyBtn56893").addEventListener("click", copyCodeToClipboard56893);
document.getElementById("runBtn56893").addEventListener("click", runCode56893);
document.getElementById("closeoutputBtn56893").addEventListener("click", closeOutput56893);


Output:

Using Apache Commons IO FileUtils Output

example.txt – Subsequent Appending:

Apache Commons IO for Java Files   
This is new content to append.

Remark: To execute the above code, you might need to include the following dependencies in your Maven Project.

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.15.1</version>
</dependency>

Summary

In this blog, we have explored how to append text to an existing file in Java using various techniques, including the java.io package, the FileOutputStream class, and the java.nio.file package, along with Apache Commons IO and Guava’s com.google.common.io.Files. You can choose any of these methods based on your project requirements.

If you wish to delve deeper into Java, you may refer to our Java course.

The article How to Append Text to an Existing File in Java? was first published on Intellipaat Blog.

```


Leave a Reply

Your email address will not be published. Required fields are marked *

Share This