java append to file code example

Example 1: file append in java

File file = new File("append.txt");
FileWriter fr = new FileWriter(file, true);
fr.write("data");
fr.close();

Example 2: how to add to a file in java

File file = new File("append.txt");
FileWriter fr = new FileWriter(file, true);
BufferedWriter br = new BufferedWriter(fr);
PrintWriter pr = new PrintWriter(br);
pr.println("data");
pr.close();
br.close();
fr.close();

Example 3: printwriter java append to file

public static void usingPrintWriter() throws IOException 
{
    String textToAppend = "Happy Learning !!";
     
    FileWriter fileWriter = new FileWriter("c:/temp/samplefile.txt", true); //Set true for append mode
    PrintWriter printWriter = new PrintWriter(fileWriter);
    printWriter.println(textToAppend);  //New line
    printWriter.close();
}

Example 4: file append in java

File file = new File("append.txt");
FileWriter fr = new FileWriter(file, true);
BufferedWriter br = new BufferedWriter(fr);
br.write("data");

br.close();
fr.close();

Example 5: append to file in java

File file = new File("append.txt");
FileWriter fr = new FileWriter(file, true); // parameter 'true' is for append mode
fr.write("data");
fr.close();

Example 6: java append a string to file

try {
    Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
    //exception handling left as an exercise for the reader
}

Tags:

Java Example