【问题标题】:Unable to write to the file, Created in java using File class无法写入文件,使用 File 类在 java 中创建
【发布时间】:2016-12-25 13:00:14
【问题描述】:

MakeDirectory 类包含构造函数,在构造函数中我创建了一个目录,并在该目录中创建了一个文件。但是即使文件和目录已成功生成,我也无法向新创建的文件写入任何内容。谁能帮我弄清楚为什么我无法写入文件anything.txt?

public class MakeDirectory {
    MakeDirectory() throws IOException{
        // Creates Directory
        File mydir= new File("MyDir");
        mydir.mkdir();

        // Creates new file object
        File myfile = new File("MyDir","Anyfile.txt");

        //Create actual file Anyfile.txt inside the directory
        PrintWriter pr= new PrintWriter(myfile);
        pr.write("This file is created through java");
    }

    public static void main(String args[]) throws IOException {
        new MakeDirectory();
    }
}

【问题讨论】:

  • 你遇到什么错误?
  • 我没有收到任何错误。文件已在该特定目录下成功生成,但是当我看到文件 Anything.txt 时,我总是发现它是空的。不包含单词或字符串。
  • 我们可以看看你用来写在这个文件中的代码吗?
  • 上面提到的代码是实际的代码先生..

标签: java file-handling


【解决方案1】:

如果你想使用PrintWriter,你需要知道它不会自动刷新。在您write 之后,您需要flush。另外,别忘了关闭你的PrintWriter

PrintWriter pw = new PrintWriter(myFile);
pw.write("text");
pw.flush();
pw.close();

Java 7 中可用的一种方法使用 try-with-resources 构造。使用此功能,代码将如下所示:

try (PrintWriter pw = new PrintWriter("myFile")) {
    pw.write("text");
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

【讨论】:

  • 先生...您成就了我的一天..终于我得到了答案...它奏效了...您想详细说明一下吗?为什么我们需要为 PrintWriter 而不是 FileWriter 等其他类强制刷新和关闭
  • 当然,您必须刷新,因为在您这样做之前,文本位于缓冲区中。刷新该缓冲区后,文本将打印在文件中。对于像FileWriter 这样的类,该类旨在在写入时自动调用该函数。
  • 哦,太好了……我会把这件事记在心里……谢谢,stackover流程太棒了。我很快就从 Java 的老手那里得到了解决方案。再次感谢先生。你做得很好,让我们理解了 java 的概念。我是新来的,所以无法抗拒自己表达我的感激之情。
【解决方案2】:

使用BufferedWriter,您可以直接将字符串、数组或字符数据写入文件:

void makeDirectory() throws IOException {
    // Creates Directory
    File mydir = new File("MyDir");
    mydir.mkdir();

    // Creates new file object
    File myfile = new File("MyDir", "Anyfile.txt");

    //Create actual file Anyfile.txt inside the directory
    BufferedWriter bw = new BufferedWriter(new FileWriter(myfile.getAbsoluteFile()));
    String str = "This file is created through java";

    bw.write(str);
    bw.close(); 
}

【讨论】:

  • 先生,我试过了,但新创建的文件仍然是空的。文件中没有写入任何内容。
  • 我对其进行了测试,它创建了一个 txt 文件,其中包含 String str 值文本。
  • 先生,我忘了在声明中添加 close 并且在添加 bw.close 之后它也对我有用......非常感谢
  • 当您执行close() 时,它会自动刷新缓冲区中的数据。
  • 是的,先生。非常感谢...继续帮助我。我是java新手。需要像您这样乐于帮助他人的支持者
猜你喜欢
  • 2021-03-24
  • 1970-01-01
  • 1970-01-01
  • 2014-11-01
  • 2018-09-20
  • 2013-08-17
  • 1970-01-01
  • 2014-10-30
  • 2014-10-06
相关资源
最近更新 更多