简体   繁体   English

如何在Java中将新行写入文件?

[英]How to write a new line to a file in Java?

I am using the PrintWriter class to write a new line to a file. 我正在使用PrintWriter类将新行写入文件。 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());
    }

 }

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. 通过阅读PrintWriterjavadoc ,您可以了解到,在创建一个以文件名作为构造函数参数的实例时,该文件(如果存在)将被截断为零大小。

Instead, you can use a FileWriter . 相反,您可以使用FileWriter See an example here . 在这里查看示例。 And don't miss using the overloaded constructor with the boolean parameter, eg new FileWriter("timeWorked.dat", true) , which opens the file for appending. 并且不要错过使用带有boolean参数的重载构造函数,例如new FileWriter("timeWorked.dat", true) ,它会打开文件进行附加。

From the javadoc of PrintWriter: 从PrintWriter的javadoc中:

Parameters: fileName The name of the file to use as the destination of this writer. 参数:fileName用作此编写器目标的文件名。 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: 要解决您的问题,请使用类FileWriter,如下所示:

new FileWriter("timeWorked.dat", true)

The boolean parameter true tells the FileWriter to open the File for appending. 布尔参数true告诉FileWriter打开要附加的文件。 This means the data you write to the file will bi added at the end. 这意味着您写入文件的数据将在最后添加。

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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM