简体   繁体   English

用Java写入文件

[英]Writing to a File in Java

I'm really new to Java, and I can't write to a file for some reason, my code looks like this: 我是Java新手,我出于某种原因无法写入文件,我的代码如下所示:

FileWriter fstream;
    try {
        fstream = new FileWriter(fileLocation);
        BufferedWriter out = new BufferedWriter(fstream);
        log.info("test was supposed to be written to the file");
        out.write("test");

        out.flush();
        out.close();

    } catch (IOException e) {
        log.error("File not created ", e);
    }

When I go to the fileLocation, I see my file, but it's empty. 当我进入fileLocation时,我看到了我的文件,但它是空的。 My log does say "test was supposed to be written to the file" 我的日志确实说“测试应该写入文件”

What could I be doing wrong here? 我在这里做错了什么?

Thanks! 谢谢!

UPDATE: My FileLocation variable is a string: 更新:我的FileLocation变量是一个字符串:

private String fileLocation="/Users/s/out.txt";

I'm using a Mac 我正在使用Mac

Code is fine. 代码很好。 Are you checking the right file location? 你在检查正确的文件位置吗? Perhaps you had created the file you're checking before; 也许你之前创建过你正在检查的文件; while your program could be writing elsewhere. 而你的程序可能写在别处。

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

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