Write a Java Program to Append Text to an Existing File

Java Program to Append Text to an Existing File

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Append Text to an Existing File
Java Program to Append Text to an Existing File

PROGRAM: Java Program to Append Text to an Existing File

/*Java Program to Append Text to an Existing File*/

1: Append text to existing file

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) {
}
}
}

2: Append text to an existing file using FileWriter

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) {
}
}
}

Leave a Reply

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