无法写入文件,使用文件 class 在 java 中创建

Unable to write to the file, Created in java using File class

Class 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();
    }
}

使用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(); 
}

如果你想使用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();
}