0
0

(調査中)クラスローダーを使用してリソースのURLを取得。特定のディレクトリの指定されたパターンのプロパティファイル名を取得

Posted at
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Pattern;

public class JarFileUtils {

    public static void main(String[] args) {
        try {
            // ディレクトリパスとパターンを指定
            String directoryPath = "/config";
            String pattern = ".*\\.properties";
            List<String> propertiesFiles = getPropertiesFilesFromJar(directoryPath, pattern);
            propertiesFiles.forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static List<String> getPropertiesFilesFromJar(String directoryPath, String pattern) throws IOException {
        List<String> propertiesFiles = new ArrayList<>();

        // クラスローダーを使用してリソースのURLを取得
        URL resourceURL = JarFileUtils.class.getResource(directoryPath);

        if (resourceURL != null && resourceURL.getProtocol().equals("jar")) {
            // URLをデコードしてJARファイルのパスを取得
            String jarPath = URLDecoder.decode(resourceURL.getPath(), "UTF-8").substring(5, resourceURL.getPath().indexOf("!"));

            try (JarFile jarFile = new JarFile(jarPath)) {
                Enumeration<JarEntry> entries = jarFile.entries();

                Pattern regexPattern = Pattern.compile(pattern);

                while (entries.hasMoreElements()) {
                    JarEntry entry = entries.nextElement();
                    String entryName = entry.getName();
                    
                    // 特定のディレクトリ内の指定されたパターンに一致するファイルをフィルタリング
                    if (entryName.startsWith(directoryPath.substring(1)) && regexPattern.matcher(entryName).matches()) {
                        propertiesFiles.add(entryName);
                    }
                }
            }
        } else {
            System.out.println("The resource is not inside a JAR file.");
        }

        return propertiesFiles;
    }
}
0
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
0
0