简体   繁体   English

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

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

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? 似乎找到了file.P,它只是一个txt文件,但似乎没有在其上附加任何内容? It enters the code and passes the IF statement fine, but nothing is appended to the text file? 它输入代码并通过IF语句,但是没有附加任何文本文件吗? I'm slightly stuck! 我有点卡住!

Are you sure it is finding file.P and not just creating a new one elsewhere in the file system? 您确定它正在查找file.P,而不仅仅是在文件系统中的其他位置创建一个新文件吗? Try an absolute path, just to make certain you and the program are looking at the same file. 尝试绝对路径,只是要确保您和程序正在查看同一文件。

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

1) Can you try calling the writer.flush() ? 1)您可以尝试调用writer.flush()吗? The code looks like it calls flush on close but would be better to confirm this. 该代码看起来像在关闭时调用flush,但最好确认一下。

2) Can you also print the full location of the file ? 2)您还可以打印文件的完整位置吗? Perhaps it is appending in the tmp directory or the wrong location? 也许它附加在tmp目录中或错误的位置?

Shouldn't your if statement have two apostrophes and && ? 您的if语句不应包含两个撇号和&&吗? requiring user and pass instead of no user or pass? 需要用户通过而不是没有用户或通过?

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

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

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