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.
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 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”>
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!”);
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:
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!");
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:
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!”);
"+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:
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!”);
"+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:
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();
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!");
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.
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional
Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.