Algorithm
-
Open File:
- Create a
File
object with the path to the existing file. - Use a
FileWriter
orBufferedWriter
to open the file in append mode. This ensures that new content will be added to the end of the file.
- Create a
-
Write Text:
- Create a
String
or use the text you want to append to the file.
- Create a
-
Append Text:
- Use the
write
method of theFileWriter
orBufferedWriter
to append the text to the file.
- Use the
-
Close File:
- Close the
FileWriter
orBufferedWriter
to ensure that changes are flushed and resources are released.
- Close the
Code Examples
#1 Code Example- Java Programing Append text to existing file
Code -
Java Programming
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class AppendFile {
public static void main(String[] args) {
String path = System.getProperty("user.dir") + "\\src\\test.txt";
String text = "Added text";
try {
Files.write(Paths.get(path), text.getBytes(), StandardOpenOption.APPEND);
} catch (IOException e) {
}
}
}
Copy The Code &
Try With Live Editor
Output
This is a
Test file.Added text
Test file.Added text
#2 Code Example- Java Programing Append text to an existing file using FileWriter
Code -
Java Programming
import java.io.FileWriter;
import java.io.IOException;
public class AppendFile {
public static void main(String[] args) {
String path = System.getProperty("user.dir") + "\\src\\test.txt";
String text = "Added text";
try {
FileWriter fw = new FileWriter(path, true);
fw.write(text);
fw.close();
}
catch(IOException e) {
}
}
}
Copy The Code &
Try With Live Editor
Output
This is a
Test file.Added text
Test file.Added text
Demonstration
Java Programing Example to Append Text to an Existing File-DevsEnv