java 写入文件而不覆盖该文件中的现有数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26525749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:05:03  来源:igfitidea点击:

Write to a file without overwriting the existing data within that file

javafilewriter

提问by Kharbora

I have a filewriter that takes String data from the user and writes it on the file. But the filewriter replaces the already existing data in that file. How do I prevent it from doing it? I just want to keep adding information without writing over something.

我有一个文件编写器,它从用户那里获取字符串数据并将其写入文件。但是文件编写器会替换该文件中已经存在的数据。我如何防止它这样做?我只想继续添加信息而不是写一些东西。

Here is the code

这是代码

    String info = scan.nextLine();
    File myFile = new File ("/home/greg/workspace/Mavericks/fred.txt");
    FileWriter writer = new FileWriter (myFile);
    writer.write(register);
    writer.flush();

Thanks. I fixed that. Now I just want to make the writer write using spaces. When I write to the file it just keeps writing within the same line.

谢谢。我修好了。现在我只想让作者使用空格来写作。当我写入文件时,它只会在同一行内写入。

回答by Ondrej Tokar

Use second parameter of FileWriter, which is defining if you want to append or not. Just set it to true.

使用 FileWriter 的第二个参数,它定义是否要附加。只需将其设置为true.

BufferedWriter writer = new BufferedWriter(new FileWriter(
                sFileName, true));

Add \nafter each line.

\n在每行之后添加。

回答by Santhosh

You need use the boolean value true. From docs

您需要使用布尔值true。来自文档

public FileWriter(String fileName,
          boolean append)
           throws IOException

Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.

构造一个 FileWriter 对象,给定一个带有布尔值的文件名,指示是否附加写入的数据。

Parameters:

参数:

fileName- String The system-dependent filename.

fileName- String 系统相关文件名。

append- boolean if true, then data will be written to the end of the file rather than the beginning.

append- boolean 如果为 true,则数据将写入文件的末尾而不是开头。

回答by Beri

Api:

接口:

FileWriter(File file, boolean append)

Constructs a FileWriter object given a File object.

给定一个 File 对象构造一个 FileWriter 对象。

http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html

http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html

回答by Terry Storm

FileWriter has an optional boolean in the constructor, which declares if it should be appended or not.

FileWriter 在构造函数中有一个可选的布尔值,它声明是否应该附加。

FileWriter writer = new FileWriter(..., true)

回答by DeiAndrei

Use

利用

new FileWriter(myFile, true)

The second parameter is for appending.

第二个参数用于追加。

回答by Prashant

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

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