Question

I am trying to make a simple program that will constantly add content to a text file, the problem with the code that I have so far is that have the previous content erased over the new content that I am trying to save. What I need to change to make my program add content and not to delete the previous one. Here is my class that I wrote so far...

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class TxtWriter{
private String content;
private File file;
private FileWriter fw;

//constractor
public TxtWriter(){
    content += "";
    file = new File("C:/Users/Geroge/SkyDrive/Documents/Java programs/FileWriter/inputFile.txt");
}
//write method
public void writeToFile(String date,double duration,double brakeDur){
    try {

        String content = "DATE: " + date + "| Shift duration: " + duration + "| brakeDur: " + brakeDur + "| Total hours: " + (duration - brakeDur) + "\n";

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }


        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.newLine();
        bw.close();

        System.out.println("Done");

    } catch (IOException e) {
        e.printStackTrace();
    }
}//end of writeToFile method

}

Was it helpful?

Solution

Use FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);

FileWriter(File file, boolean append)
Constructs a FileWriter object given a File object.
Parameters:
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the file rather than the beginning.

from here.

OTHER TIPS

Use the new file API!

In your constructor, declare a Path, not a File:

targetFile = Paths.get("C:/Users/Geroge/SkyDrive/Documents/Java programs/FileWriter/inputFile.txt");

In your function which appends:

try (
    // Note the options: create if not exists; append if exists
    final BufferedWriter = Files.newBufferedWriter(targetFile, StandardCharsets.UTF_8,
        StandardOpenOption.CREATE, StandardOpenOption.APPEND);
) {
    // write contents to file
} // Automatically closed for you here

Drop File!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top