java append file

java append file

To append text to a file in Java, you can use the FileWriter class and the BufferedWriter class.

Here is an example of how to append text to a file using these classes:

import java.io.*;

public class AppendFileExample {

    public static void main(String[] args) {
        String fileName = "file.txt";
        String text = "This is some text to be appended to the file.";

        try {
            // Open the file in append mode
            FileWriter fileWriter = new FileWriter(fileName, true);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

            // Write the text to the file
            bufferedWriter.write(text);
            bufferedWriter.newLine();

            // Close the file
            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
So‮www:ecru‬.lautturi.com

In this example, the FileWriter class is used to open the file in append mode (the true argument to the constructor indicates that the file should be opened in append mode). The BufferedWriter class is then used to write the text to the file and to add a new line after the text. Finally, the close() method is called to close the file and release any resources associated with it.

Note that the FileWriter and BufferedWriter classes can throw an IOException if an I/O error occurs while working with the file. It is recommended to handle this exception in a try-catch block to prevent the program from crashing.

Created Time:2017-11-03 00:14:42  Author:lautturi