1

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

 }
informatik01
  • 16,038
  • 10
  • 74
  • 104
Andres Rivera
  • 97
  • 2
  • 7
  • You're reading and writing the same file at the same time? Intentionally? – dcsohl Nov 22 '13 at 21:03
  • Yes I did the readFile to check if file has a line, If it does than I want it to write a new line without over writing the old line but can't get it to work. – Andres Rivera Nov 22 '13 at 21:07

3 Answers3

3

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.

Andrei Nicusan
  • 4,555
  • 1
  • 23
  • 36
2

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.

0

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");
Oleg Mikhailov
  • 5,751
  • 4
  • 46
  • 54