原文: https://beginnersbook.com/2014/01/how-to-create-a-file-in-java/
在本教程中,我们将了解如何使用createNewFile()方法在 Java 中创建文件。如果文件在指定位置不存在并且返回true,则此方法创建一个空文件。如果文件已存在,则此方法返回false。它抛出:
IOException - 如果在创建文件期间发生输入/输出错误。
SecurityException - 如果存在安全管理器且其SecurityManager.checkWrite(java.lang.String))方法拒绝对该文件的写访问。
完整代码:
下面的代码将在 C 盘中创建一个名为newfile.txt的txt文件。您可以更改以下代码中的路径,以便在不同目录或不同驱动器中创建文件。
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();}}}
