「Java8」クラスFileのgetNameメソッドでファイルまたはディレクトリの名前を返す

2022年7月1日

環境
Java 1.8
Eclipse 4.14.0

構文
1.createNewFile()
この抽象パス名が示す空の新しいファイルを不可分 (atomic) に生成します (その名前のファイルがまだ存在しない場合だけ)。
2.getParent()
この抽象パス名の親のパス名文字列を返します。このパス名が親ディレクトリを示さない場合は null を返します。
3.public boolean exists()
この抽象パス名が示すファイルまたはディレクトリが存在するかどうかを判定します。
4.getAbsolutePath()
この抽象パス名の絶対パス名文字列を返します。
5.getName()
この抽象パス名が示すファイルまたはディレクトリの名前を返します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
import java.io.File;
import java.io.IOException;
public class FilecreateSample {
public static void main(String[] args) throws IOException {
String filename = "d:\\test\\demo.csv";
File ff = new File(filename);
if (!ff.exists()) {
ff.createNewFile();
}
/* 親ディレクトリのパスを取得 */
System.out.println("親ディレクトリ:" + ff.getParent());
/* ファイルかどうか判定 */
System.out.println("ファイル判定:" + ff.isFile());
/* ファイル存在判定 */
System.out.println("ファイル存在:" + ff.exists());
/* 絶対パスの取得 */
System.out.println("絶対パス:" + ff.getAbsolutePath());
/*ファイル名の取得*/
System.out.println("ファイル名:"+ff.getName());
}
}
package com.arkgame.study; import java.io.File; import java.io.IOException; public class FilecreateSample { public static void main(String[] args) throws IOException { String filename = "d:\\test\\demo.csv"; File ff = new File(filename); if (!ff.exists()) { ff.createNewFile(); } /* 親ディレクトリのパスを取得 */ System.out.println("親ディレクトリ:" + ff.getParent()); /* ファイルかどうか判定 */ System.out.println("ファイル判定:" + ff.isFile()); /* ファイル存在判定 */ System.out.println("ファイル存在:" + ff.exists()); /* 絶対パスの取得 */ System.out.println("絶対パス:" + ff.getAbsolutePath()); /*ファイル名の取得*/ System.out.println("ファイル名:"+ff.getName()); } }
package com.arkgame.study;

import java.io.File;
import java.io.IOException;
public class FilecreateSample {

      public static void main(String[] args) throws IOException {

            String filename = "d:\\test\\demo.csv";
            File ff = new File(filename);

            if (!ff.exists()) {
                  ff.createNewFile();
            }
            /* 親ディレクトリのパスを取得 */
            System.out.println("親ディレクトリ:" + ff.getParent());

            /* ファイルかどうか判定 */
            System.out.println("ファイル判定:" + ff.isFile());

            /* ファイル存在判定 */
            System.out.println("ファイル存在:" + ff.exists());

            /* 絶対パスの取得 */
            System.out.println("絶対パス:" + ff.getAbsolutePath());
            
            /*ファイル名の取得*/
            System.out.println("ファイル名:"+ff.getName());

      }

}

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
親ディレクトリ:d:\test
ファイル判定:true
ファイル存在:true
絶対パス:d:\test\demo.cvs
ファイル名:demo.cvs
親ディレクトリ:d:\test ファイル判定:true ファイル存在:true 絶対パス:d:\test\demo.cvs ファイル名:demo.cvs
親ディレクトリ:d:\test
ファイル判定:true
ファイル存在:true
絶対パス:d:\test\demo.cvs
ファイル名:demo.cvs

 

Java

Posted by arkgame