Andres Rivera
Andres Rivera

Reputation: 97

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

 }

Upvotes: 1

Views: 2822

Answers (3)

Oleg Mikhailov
Oleg Mikhailov

Reputation: 6081

This works for me:

File file = new File("output.txt");
FileOutputStream outputStream = new FileOutputStream(file, false);
PrintWriter out = new PrintWriter(outputStream, true);
out.println("test");

Upvotes: 0

Silvano Brugnoni
Silvano Brugnoni

Reputation: 424

From the javadoc of PrintWriter:

Parameters: fileName The name of the file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.

I guess that's the problem :)

To fix your Problem, use the class FileWriter as follows:

new FileWriter("timeWorked.dat", true)

The boolean parameter true tells the FileWriter to open the File for appending. This means the data you write to the file will bi added at the end.

Upvotes: 2

Andrei Nicusan
Andrei Nicusan

Reputation: 4623

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.

Upvotes: 3

Related Questions