Javaでファイルとディレクトリを作成

内容

Javaでファイルとディレクトリを作成する。

ファイル

new File("ファイル名") でFileクラスのインスタンスを作成する。

createNewFile()でインスタンス作成時の引数に指定したファイルがカレントディレクトリに作成される。

exists()でファイルが存在するか確認できる。

ディレクト

ファイルと同じようにnew File("ディレクトリ名")でFileクラスのインスタンスを作成する。

mkdir()でインスタンス作成時の引数に指定したディレクトリがカレントディレクトリに作成される。

exists()でディレクトリが存在するか確認できる。

ソース

どちらもgetAbsolutePath()を使うとルートディレクトリからの絶対パスが取得できる。

import java.io.File;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        File file = new File("data.txt");
        File dir = new File("data");
        try {
            // ファイルが存在しなければファイルを作成
            if (!file.exists()) {
                file.createNewFile();
                System.out.println(file.getAbsolutePath());
            }
            // ディレクトリがなければ作成
            if (!dir.exists()) {
                dir.mkdir();
                System.out.println(dir.getAbsolutePath());
            }
        } catch (IOException e) {
            System.out.println(e);
            e.printStackTrace();
        }
    }
}