java file system append new line

ht‮/:spt‬/www.lautturi.com
java file system append new line

To append a new line to a file in Java, you can use the BufferedWriter class. Here's an example of how to do it:

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class Main {
  public static void main(String[] args) {
    String fileName = "file.txt";
    String line = "This is a new line.";

    try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true))) {
      writer.write(line);
      writer.newLine();
      writer.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

This code will open the file with the specified name (in this case, "file.txt"), and append the specified line to it, followed by a new line. If the file doesn't exist, it will be created.

Note that this code uses a try-with-resources statement to ensure that the BufferedWriter is closed properly, even if an exception is thrown. It's important to close resources like this to avoid leaking them and potentially running out of resources.

Created Time:2017-11-03 15:57:13  Author:lautturi