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.
File Handling Examples
- How to Create a New File in Java
- How to Write to File in Java
- How to delete a file in Java
- How to Copy the File in Java
- How to Move a File in Java
- How to Rename the File in Java
- How to Append to File in Java
- Read the File using BufferReader
- Read File using BufferInputStream
- Read the File using DataInputStream
- Reading a File in Java using BufferedInputStream
- Read a File in Java using BufferedReader
- Java Get File Extension From Filename
- Get File Size in Bytes KB MB GB TB
- How to Check if a File is Empty in Java
Comments
Post a Comment
Leave Comment