-1

我想将一些数据写入 .txt 文件。

     public void writeToFile(String filename) {

    try {

        //Construct the BufferedWriter object
        bufferedWriter = new BufferedWriter(new FileWriter(filename));

        //Start writing to the output stream
        bufferedWriter.write("first value : " + firstValue);
        bufferedWriter.newLine();

    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        //Close the BufferedWriter
        try {

           if (bufferedWriter != null) {
               bufferedWriter.flush();
                bufferedWriter.close();
            }
        } catch (IOException ex) {
           ex.printStackTrace();
        }
    }
}

我使用这段代码,但问题是它会不断覆盖第一行(我认为)。有谁知道我该如何解决这个问题?我从串口读取everey 50ms 的值,不想写这个。(每个值都在单独的一行)

它应该写值,直到我关闭程序。

此致

4

2 回答 2

1

尝试换行:

bufferedWriter = new BufferedWriter(new FileWriter(filename));

至:

bufferedWriter = new BufferedWriter(new FileWriter(filename, true));

我将以追加模式打开 FileWrite,它会在文件中添加内容,而不是覆盖它。

于 2013-02-22T13:47:03.543 回答
1

像这样打开作家:

bufferedWriter = new BufferedWriter(new FileWriter(filename, true));

那应该打开文件进行附加。请参阅javadoc

于 2013-02-22T13:47:09.403 回答