💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 如何在 Java 中创建文件 > 原文: [https://beginnersbook.com/2014/01/how-to-create-a-file-in-java/](https://beginnersbook.com/2014/01/how-to-create-a-file-in-java/) 在本教程中,我们将了解如何使用`createNewFile()`方法在 Java 中创建文件。如果文件在指定位置不存在并且返回`true`,则此方法创建一个空文件。如果文件已存在,则此方法返回`false`。它抛出: [`IOException`](https://docs.oracle.com/javase/7/docs/api/java/io/IOException.html) - 如果在创建文件期间发生输入/输出错误。 [`SecurityException`](https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityException.html) - 如果存在安全管理器且其[`SecurityManager.checkWrite(java.lang.String)`](https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityManager.html#checkWrite(java.lang.String))方法拒绝对该文件的写访问。 **完整代码:** 下面的代码将在 C 盘中创建一个名为`newfile.txt`的`txt`文件。您可以更改以下代码中的路径,以便在不同目录或不同驱动器中创建文件。 ```java package beginnersbook.com; import java.io.File; import java.io.IOException; public class CreateFileDemo { public static void main( String[] args ) { try { File file = new File("C:\\newfile.txt"); /*If file gets created then the createNewFile() * method would return true or if the file is * already present it would return false */ boolean fvar = file.createNewFile(); if (fvar){ System.out.println("File has been created successfully"); } else{ System.out.println("File already present at the specified location"); } } catch (IOException e) { System.out.println("Exception Occurred:"); e.printStackTrace(); } } } ``` #### 参考: [Javadoc:`createNewFile()`](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createNewFile())