使用 Java 建立新的空檔案


可以使用 java.io.File.createNewFile() 方法建立一個具有所需抽象路徑名的新的空檔案。此方法不需要任何引數,如果檔案是新建立的並且之前不存在,則返回 true。如果檔案之前存在,則返回 false。

一個演示此功能的程式如下所示 −

示例

 線上演示

import java.io.File;
public class Demo {
   public static void main(String[] args) {
      try {
         File file = new File("demo1.txt");
         file.createNewFile();
         System.out.println("File: " + file);
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

以上程式的輸出如下 −

輸出

File: demo1.txt

現在讓我們來理解上述程式。

該檔案是使用 java.io.File.createNewFile() 方法建立的。然後列印檔名。一個演示此功能的程式碼片段如下 −

try {
   File file = new File("demo1.txt");
   file.createNewFile();
   System.out.println("File: " + file);
} catch(Exception e) {
   e.printStackTrace();
}

更新於: 30-Jul-2019

12K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告