Writing text files using Java

This simple method shows hot to write to text files using Java.
If the file exists it will append the new text to it, otherwise it creates a new file. This is achieved using the FileWriter class and its constructor:

public FileWriter(String fileName, boolean append) throws IOException

Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written. JavaDoc.

public void writeToFile(String text, String filePath){
 
  try {
 
    File thisFile = new File(filePath);
 
    BufferedWriter writer = new BufferedWriter(
                                new FileWriter(filePath, thisFile.exists()));
    writer.write( text );
    writer.newLine();
 
    writer.flush();
    writer.close();
 
  } catch (IOException e) {
    e.printStackTrace();
  }
}

Leave a Reply