Search code examples
javaprintwriter

How to write a new line to a file in Java?


I am using the PrintWriter class to write a new line to a file. It writes the line as expected, but when I want to write new data it over writes the old data instead of writing a new line. Here is what I have so far.

import javax.swing.*;
import java.text.*;
import java.util.*;
import java.io.*;

public class TimeTracker 
{

    /**
    * @param args the command line arguments
    * @throws java.io.FileNotFoundException
    */
    public static void main(String[] args) throws FileNotFoundException 
    {
        DecimalFormat money = new DecimalFormat("$#,##0.00");
        PrintWriter toFile = new PrintWriter("timeWorked.dat");
        Scanner readFile = new Scanner(new FileReader("timeWorked.dat"));

        String client = JOptionPane.showInputDialog("Client's Name");
        int rate = Integer.parseInt(JOptionPane.showInputDialog("Rate per hour?"));
        String output;
        output = "Client's Name: " + client +
                 " Pay rate agreed: " + money.format(rate) + " per hour";
        toFile.append(output);
        toFile.flush();          
        if (readFile.hasNext())
        {
            toFile.append("\n");
            toFile.write(output);
            toFile.flush();
        }
        JOptionPane.showMessageDialog(null, readFile.nextLine());
    }

 }

Solution

  • By reading the javadoc of PrintWriter, you can learn that when creating an instance with the file name as constructor parameter, the file - if existent - will be truncated to zero size.

    Instead, you can use a FileWriter. See an example here. And don't miss using the overloaded constructor with the boolean parameter, e.g. new FileWriter("timeWorked.dat", true), which opens the file for appending.