Java 创建文件
创建文件
要在 Java 中创建文件,可以使用 createNewFile() 方法。此方法返回一个布尔值:如果成功创建文件,则返回 true;如果文件已存在,则返回 false。
请注意,该方法应该包含在 try…catch 块中,这是必要的,因为如果发生错误(如果由于某种原因无法创建文件),它可以引发 IOException:
实例
import java.io.File; // Import the File classimport java.io.IOException; // Import the IOException class to handle errorspublic class CreateFile {public static void main(String[] args) {try {File myObj = new File("filename.txt");if (myObj.createNewFile()) {System.out.println("File created: " + myObj.getName());} else {System.out.println("File already exists.");}} catch (IOException e) {System.out.println("An error occurred.");e.printStackTrace();}}}
输出将为:
File created: filename.txt
要在特定目录中创建文件(需要权限),请指定文件路径,并使用双反斜杠转义 "\" 字符(对于 Windows)。在 Mac 和 Linux 上,您只需编写路径,如:/Users/name/filename.txt
实例
import java.io.File;import java.io.IOException;public class CreateFileDir {public static void main(String[] args) {try {File myObj = new File("C:\\Users\\MyName\\filename.txt");if (myObj.createNewFile()) {System.out.println("File created: " + myObj.getName());System.out.println("Absolute path: " + myObj.getAbsolutePath());} else {System.out.println("File already exists.");}} catch (IOException e) {System.out.println("An error occurred.");e.printStackTrace();}}}