Write lines of text to file using a PrintWriter



This example shows how to write multiple lines of text to a file.
The method writeLinesToFile takes three arguments:

1. The name of the file, could be an absolute path but in the example just a filename
so it will be created in the current directory.

2. An array of Strings where each element is one line in the file.

3. A boolean value to determine if any existing file with the same name should be
appended to or not. In the example we choose to append.




import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class FileUtil {

  public void writeLinesToFile(String filename,
                               String[] linesToWrite,
                               boolean appendToFile) {

    PrintWriter pw = null;

    try {

      if (appendToFile) {

        //If the file already exists, start writing at the end of it.
        pw = new PrintWriter(new FileWriter(filename, true));

      }
      else {

        pw = new PrintWriter(new FileWriter(filename));
        //this is equal to:
        //pw = new PrintWriter(new FileWriter(filename, false));

      }

      for (int i = 0; i < linesToWrite.length; i++) {

        pw.println(linesToWrite[i]);

      }
      pw.flush();

    }
    catch (IOException e) {
      e.printStackTrace();
    }
    finally {
      
      //Close the PrintWriter
      if (pw != null)
        pw.close();
      
    }

  }

  public static void main(String[] args) {
    FileUtil util = new FileUtil();
    util.writeLinesToFile("myfile.txt", new String[] {"Line 1",
                                                      "Line 2",
                                                      "Line 3"}, true);
  }
}
 





   What kind of Java example would you like to see on this site?

   
     E-mail (optional)