0
1

More than 3 years have passed since last update.

【Java】フォルダ内のファイルパスをListで取得

Posted at

引数のフォルダ内にあるファイルの一覧をStringのListにしてみるメソッド。
※再帰的に呼び出してListにaddAllしてみた
※Java8~15で動作検証済み(不具合あっても責任は取らない方向で

FileUtils

import java.io.File;
import java.util.LinkedList;
import java.util.List;

public class FileUtils {

    /**
     * 引数のディレクトリ内にあるフォルダやファイルのPathを文字列のListで返す
     *
     * @param root
     * @return
     */
    public static List<String> getFileList(String root) {
        return getFileList(new File(root));
    }

    /**
     *
     * 引数のディレクトリ内にあるフォルダやファイルのPathを文字列のListで返す
     *
     * @param root
     * @return
     */
    public static List<String> getFileList(File root) {
        return getFileList(root, null);
    }

    /**
     *
     * 引数のディレクトリ内にあるフォルダやファイルのPathを文字列のListで返す
     *
     * @param root
     * @param fileList
     * @return
     */
    private static List<String> getFileList(File root, List<String> fileList) {
        // 引数のフォルダが存在しない場合はnullを返す
        if (root == null || !root.exists())
            return null;
        if (fileList == null)
            fileList = new LinkedList<>();
        if (root.isDirectory())
            for (File f : root.listFiles())
                fileList.addAll(getFileList(f, null));
        else
            fileList.add(root.getPath());
        return fileList;
    }
}

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1