Java-io-file-exists

提供:Dev Guides
移動先:案内検索

Java.io.File.exists()メソッド

説明

  • java.io.File.exists()*メソッドは、この抽象パス名で定義されたファイルまたはディレクトリの存在をテストします。

宣言

以下は* java.io.File.exists()*メソッドの宣言です-

public boolean exists()

パラメーター

NA

戻り値

このメソッドは、抽象パス名で定義されたファイルが存在する場合にのみブール値trueを返します。そうでない場合は偽。

例外

NA

次の例は、java.io.File.exists()メソッドの使用法を示しています。

package com.finddevguides;

import java.io.File;

public class FileDemo {
   public static void main(String[] args) {
      File f = null;
      boolean bool = false;

      try {
        //create new files
         f = new File("test.txt");

        //create new file in the system
         f.createNewFile();

        //tests if file exists
         bool = f.exists();

        //prints
         System.out.println("File exists: "+bool);

         if(bool == true) {
           //delete() invoked
            f.delete();
            System.out.println("delete() invoked");
         }

        //tests if file exists
         bool = f.exists();

        //prints
         System.out.print("File exists: "+bool);

      } catch(Exception e) {
        //if any error occurs
         e.printStackTrace();
      }
   }
}

上記のプログラムをコンパイルして実行すると、次の結果が生成されます-

File exists: true
delete() invoked
File exists: false