如何在 Java 中创建文件?

How Can I Create A File In Java?

我正在开发一个需要大量应用数据的程序。我正在尝试创建一个函数,该函数使用字符串路径的 path/file 名称创建一个文件。这是我的代码:

public static void CreateFile(String path) throws FileNotFoundException, UnsupportedEncodingException {

    PrintWriter writer = new PrintWriter(path, "UTF-8");
    writer.close();

}

我做错了什么?它不应该创建一个文件吗?

请参阅文档中的 this link - 创建一个文件对象,然后对新创建的对象调用 'createNewFile()' 方法。

您似乎想要创建一个空文件。为此,您可以使用 Files.createFileFile.createNewFile(但它需要您实例化一个 File)。

要创建一个非空文件,只要在里面写点东西,如果不存在就会自动创建。

你可以参考这段代码:

     FileWriter fw = new FileWriter("C:\FileW3.txt");// you can give path here

//or
            FileOutputStream fos = new FileOutputStream("path name");
            PrintWriter pw = new PrintWriter (new OutputStreamWriter(fos));
            pw.write("Combo stream and writer + using PrintWriter's write() methood/n");
            pw.println();
            pw.println("now using PrintWriter's println() methood");
            pw.flush();
            pw.close();

还有

File f = new File("path and filename");

这不会创建文件,文件对象可以用作 FileWriter 或 FileOutputStream 中的参数来创建然后写入该文件。 文件对象只是文件的抽象表示。