如何在java中向txt文件添加内容

时间:2014-04-05 18:30:01

标签: java file text add

我正在尝试制作一个简单的程序,它会不断地将内容添加到文本文件中,到目前为止我所拥有的代码的问题是先前的内容已经删除了我想要保存的新内容。我需要更改以使我的程序添加内容而不删除上一个内容。这是我到目前为止写的课程......

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

}

2 个答案:

答案 0 :(得分:3)

使用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.

来自here

答案 1 :(得分:1)

使用新文件API!

在构造函数中,声明Path,而不是File

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

在你追加的功能中:

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

放弃File