1. Overview
In Java, we can use FileWriter(file, true) to append new content to the end of a file.
- All existing content will be overridden.
new FileWriter(file);
- Keep the existing content and append the new content to the end of a file.
new FileWriter(file,true);
2. FileWriter – Append file example
- Let's create a file "sample.txt" under a directory "C:/workspace".
- Keep some content in file C:/workspace/sample.txt like
There is some content in file
- Let's Java example to append new content to the end of a file.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This Java program demonstrates how to append content to existing file contents.
* @author javaguides.net
*/
public class AppendFileExample {
private static final Logger LOGGER = LoggerFactory
.getLogger(AppendFileExample.class);
public static void main(String[] args) {
appendToExitingFile();
}
public static void appendToExitingFile(){
try (Writer writer = new FileWriter("C:/workspace/sample.txt",true);
BufferedWriter bw = new BufferedWriter(writer)) {
String content = "append something to existing file\n";
bw.write(content);
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
}
}
Output: Let's open the "sample.txt" and verify the content.
There is some content in file append something to existing file
User Writer interface as reference type so it provides loose coupling. In the future, we may use some other Writer classes.
3. Reference
https://docs.oracle.com/javase/8/docs/api/java/io/FileWriter.htmlhttps://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course
Comments
Post a Comment