简体   繁体   English

打印到文件的更改未保存

[英]Changes printed to a file aren't being saved

try{


 private fileWriter= new PrintWriter(new FileWriter(file.txt));
                fileWriter.print("hello world");
                System.out.println("file written");

                fileWriter.close();
}
catch (IOException e){
            e.printStackTrace();

        } finally {
        }

I have this text file in my source folder. 我的源文件夹中有这个文本文件。 So far, there haven't been any errors with accessing it. 到目前为止,访问它没有任何错误。 However, when I close the program or after when the files should have been written when I open the text file I don't find them there, however I did check the bin folder ocne and it seemed to print hello world to the temp copy there. 但是,当我关闭程序或在我打开文本文件时应该写入文件之后我没有在那里找到它们,但是我确实检查了bin文件夹ocne并且它似乎打印了hello world到temp copy那里。

I want the changes it makes to be permanent. 我希望它所做的改变是永久性的。

You have a couple of problems in your code. 您的代码中存在一些问题。 Correcting/simplifying it to the following: 将其更正/简化为以下内容:

public static void main(String[] args) throws IOException {
    PrintWriter fileWriter = new PrintWriter(new FileWriter(new File("file.txt")));
    fileWriter.print("hello world");
    System.out.println("file written");
    fileWriter.close();
}

makes it create the file as expected. 使它按预期创建文件。 Try that out, and if it doesn't behave the way you're expecting, then explain how. 尝试一下,如果它没有按照你期望的方式行事,那么解释一下。 Note that when you give a relative file path, it resolves the path against your current working directory. 请注意,当您提供相对文件路径时,它会根据您当前的工作目录解析路径。 If the file is being written somewhere you don't expect, this is probably why. 如果文件是在你不想要的地方写的,这可能就是原因。

The file in the bin folder is not a temp file, it is the file you are actually writing. bin文件夹中的文件不是临时文件,而是您实际编写的文件。 If you want to write to the file in the source folder you have to use it's correct file path when opening the file for writing. 如果要写入源文件夹中的文件,则在打开文件进行写入时必须使用正确的文件路径。 Java always computes relative paths to the folder you started your application in. So your application is probably started in the bin folder and writes to file.txt there. Java总是计算启动应用程序的文件夹的相对路径。因此,您的应用程序可能在bin文件夹中启动并写入file.txt。

Maybe try using the append boolean in the FileWriter constructor 也许尝试在FileWriter构造函数中使用append boolean

public FileWriter(String fileName, boolean append) public FileWriter(String fileName,boolean append)

...and I think eclipse will use the bin folder as its default classpath so its no surprise the file is written there. ...而且我认为eclipse将使用bin文件夹作为其默认的类路径,因此在那里编写文件并不奇怪。

I hope that helps :) 我希望有帮助:)

由于代码可以很好地进入包资源管理器 - >项目 - >属性 - > java构建路径 - >源代码 - >选中“允许源文件夹输出”的复选框

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

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