【问题标题】:How to add content to a txt file in java如何在java中将内容添加到txt文件
【发布时间】:2014-04-05 18:30:00
【问题描述】:

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

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

}

【问题讨论】:

标签: java file text add


【解决方案1】:

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

【讨论】:

  • Java 8 已经过时了,所以至少要宣传一下已经有几年历史的 Files... 比 File 优越得多,根本没有可比性
  • 非常感谢!所以我只需要在 fw 对象的构造函数中是真的! :)
  • @BogGogo 使用新的 API。严重地。它允许更理智、更安全的文件操作
  • 非常感谢您的建议和帮助! :)
【解决方案2】:

使用新的文件 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

【讨论】:

    猜你喜欢
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    相关资源
    最近更新 更多