chikuchikugonzalezの雑記帳

趣味とか日記とかメモとか(∩゚д゚)

リソースを含んでいるクラスパスエントリ自体を取得したかった

当初の目的は「java -jar 」で起動したjarファイルのパスを知りたかったこと。exeファイルみたいに実行可能ファイルのあるディレクトリの下に設定用ディレクトリを作りたかったのです。
最初は全部のクラスパスを探してましたが、ClassLoader#getResource()の存在を思い出したので、とりあえずリソースとその親のパスをURLで返すコードを書いてみた。

import java.io.File;
import java.net.URI;
import java.net.URL;

public class ClassPathUtil {

    public static enum Protocol {

        FILE_PROTOCOL("file"),
        JAR_FILE_PROTOCOL("jar");

        private String protocolPrefix = null;

        private Protocol(String prefix) {
            this.protocolPrefix = prefix;
        }

        public String getPrefix() {
            return this.protocolPrefix;
        }

    }

    public static void main(String[] args) {
        if (args.length > 0) {
            ClassPathUtil util = new ClassPathUtil();
            URL resource = util.getResource(args[0]);
            URL parent = util.getResourceParent(args[0]);
            System.out.println("Resource : " + resource);
            System.out.println("  Parent : " + parent);
        }
    }

    private ClassLoader classLoader = null;

    public ClassPathUtil() {
        this(ClassLoader.getSystemClassLoader());
    }

    public ClassPathUtil(ClassLoader loader) {
        super();
        this.classLoader = loader;
    }

    public URL getResource(String name) {
        return this.classLoader.getResource(name);
    }

    public URL getResourceParent(String name) {
        URL resource = this.getResource(name);
        if (resource != null) {
            try {
                String protocol = resource.getProtocol();
                if (Protocol.FILE_PROTOCOL.getPrefix().equals(protocol)) {
                    return new File(resource.toURI()).getParentFile().toURI().toURL();
                } else {
                    String file = resource.getFile();
                    int index = file.indexOf('!');
                    return new File(new URI(file.substring(0, index))).toURI().toURL();
                }
            } catch (Exception e) {
                return null;
            }
        } else {
            return null;
        }
    }

}