Java- FileWriter/BufferedWriter - 附加到文本文件的末尾?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2379710/
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-10-29 20:52:04  来源:igfitidea点击:

Java- FileWriter/BufferedWriter - appending to end of a text file?

javafile-io

提问by KP65

I've done this before once, I'm trying to replicate what I did so far and this is what I've got:

我以前做过一次,我试图复制我到目前为止所做的,这就是我所得到的:

    try {
        BufferedWriter writer = new BufferedWriter(new FileWriter("file.P", true));
        System.out.println("entered");
        if (!(newUserName.isEmpty()) || (newUserPass.isEmpty())){
            writer.newLine();
            writer.write("hellotest123");
            writer.close();
        }

It seems to find file.P, which is just a txt file, but it doesn't seem to append anything onto it? It enters the code and passes the IF statement fine, but nothing is appended to the text file? I'm slightly stuck!

它似乎找到了 file.P,它只是一个 txt 文件,但它似乎没有附加任何内容?它输入代码并通过 IF 语句,但文本文件中没有附加任何内容?我有点卡住了!

回答by Kris

Are you sure it is finding file.P and not just creating a new one elsewhere in the file system? Try an absolute path, just to make certain you and the program are looking at the same file.

你确定它是在寻找 file.P 而不是在文件系统的其他地方创建一个新的?尝试使用绝对路径,以确保您和程序正在查看同一个文件。

Edit:

编辑:

Based on the comment that the file is on the class path you should be using the following method of resolving it:

根据文件位于类路径上的注释,您应该使用以下方法来解决它:

MyClass.class.getResource("file.P");

This will find file.P on the classpath in the same "package" or folder as MyClass.class

这将在与 MyClass.class 相同的“包”或文件夹中的类路径上找到 file.P

回答by Kannan Ekanath

1) Can you try calling the writer.flush() ? The code looks like it calls flush on close but would be better to confirm this.

1) 你可以尝试调用 writer.flush() 吗?代码看起来像是在关闭时调用flush,但最好确认一下。

2) Can you also print the full location of the file ? Perhaps it is appending in the tmp directory or the wrong location?

2)您还可以打印文件的完整位置吗?也许它附加在 tmp 目录或错误的位置?

回答by Shane

Shouldn't your ifstatement have two apostrophes and &&? requiring user andpass instead of no user or pass?

你的if语句不应该有两个撇号和&&吗?需要用户通行证而不是没有用户或通行证?

if (!(newUserName.isEmpty()) && !(newUserPass.isEmpty())){