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);
  }
}
 

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: