1
0

Javaで、ディレクトリの一覧を取得。拡張子はproperties。List<String>に結果を格納したい

Posted at
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class PropertiesFileList {

    public static void main(String[] args) {
        // クラスパスを基準としたディレクトリのパス
        String directoryPath = "/directory"; // ディレクトリが直下にある場合

        // クラスローダーを使用してリソースを取得
        ClassLoader classLoader = PropertiesFileList.class.getClassLoader();
        URL resource = classLoader.getResource(directoryPath);

        if (resource != null) {
            // try-with-resourcesを使用してファイルリソースを自動的にクローズ
            try (var directoryStream = new File(resource.getFile()).listFiles()) {
                // 結果を格納するリスト
                List<String> propertiesFiles = new ArrayList<>();

                // ファイル一覧を走査して拡張子が.propertiesのファイルを抽出
                if (directoryStream != null) {
                    for (File file : directoryStream) {
                        if (file.isFile() && file.getName().endsWith(".properties")) {
                            propertiesFiles.add(file.getName());
                        }
                    }
                }

                // 結果を出力
                for (String fileName : propertiesFiles) {
                    System.out.println(fileName);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("ディレクトリが見つかりませんでした。");
        }
    }
}
1
0
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
1
0