Java-io-file-getname

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

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

説明

  • java.io.File.getName()*メソッドは、パス名の名前シーケンスの姓を返します。つまり、この抽象パス名で示されるファイルまたはディレクトリの名前が返されます。

宣言

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

public String getName()

パラメーター

NA

戻り値

このメソッドは、ファイルまたはディレクトリの名前、またはパス名の名前シーケンスが空の場合は空の文字列を返します。

例外

NA

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

package com.finddevguides;

import java.io.File;

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

      try {
        //create new files
         f = new File("C:\\test.txt");
         f1 = new File("C:\\Program Files");

        //get file name or directory name
         v = f.getName();
         v1 = f1.getName();

        //true if the file path exists
         bool = f.exists();

        //if file exists
         if(bool) {

           //prints
            System.out.println("File name: "+v);
         }

        //true if the directory exists
         bool = f1.exists();

        //if the folder exists
         if(bool) {

           //prints
            System.out.print("Folder name: "+v1);
         }

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

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

File name: test.txt
Folder name: Program Files