2014年1月31日 星期五

How to get the location of an executing JAR file


#-*- coding: utf-8 -*-
System.out.println("0: " + JarLocation.class.getProtectionDomain().getCodeSource().getLocation().getFile());
        System.out.println("1: " + new File(JarLocation.class.getProtectionDomain().getCodeSource().getLocation().getFile()).getCanonicalPath());
        System.out.println("2: " + JarLocation.class.getProtectionDomain().getCodeSource().getLocation().getPath());
        System.out.println("3: " + JarLocation.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
        System.out.println("4: " + new File(JarLocation.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getCanonicalPath());
        System.out.println("5: " + JarLocation.class.getClassLoader().getResource("").getPath());
        System.out.println("6: " + new File(JarLocation.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParentFile());
        System.out.println("7: " + JarLocation.class.getProtectionDomain().getCodeSource().getLocation().toString());
        System.out.println("8 :" + System.getProperty("java.class.path"));
        System.out.println("9 :" + new File(System.getProperty("java.class.path")).toURI().getPath());
        System.out.println("10 :"+ new File(System.getProperty("java.class.path")).toURI());
        System.out.println("11:" + new File(".").getAbsolutePath());
        System.out.println("12:" + new File(System.class.getResource("/").getPath()).getCanonicalPath());
        System.out.println("13:" + new File(System.class.getResource("/").toURI().getPath()));
        System.out.println("14:" + System.getProperty("user.dir"));



 執行結果:
D:\Temp>java -jar "JarLocation   space\JarLocation_package.jar"
0: ./
1: D:\Temp
2: ./
3: null
4: D:\Temp
5:
6: null
7: rsrc:./
8 :JarLocation   space\JarLocation_package.jar
9 :/D:/Temp/JarLocation   space/JarLocation_package.jar
10 :file:/D:/Temp/JarLocation%20%20%20space/JarLocation_package.jar
11:D:\Temp\.
12:D:\Temp\JarLocation%20%20%20space
13:D:\Temp\JarLocation   space
14:D:\Temp

D:\Temp>java -jar "JarLocation   space\JarLocation_extract.jar"
0: /D:/Temp/JarLocation%20%20%20space/JarLocation_extract.jar
1: D:\Temp\JarLocation%20%20%20space\JarLocation_extract.jar
2: /D:/Temp/JarLocation%20%20%20space/JarLocation_extract.jar
3: /D:/Temp/JarLocation   space/JarLocation_extract.jar
4: D:\Temp\JarLocation%20%20%20space\JarLocation_extract.jar
5: /D:/Temp/JarLocation%20%20%20space/
6: D:\Temp\JarLocation%20%20%20space
7: file:/D:/Temp/JarLocation%20%20%20space/JarLocation_extract.jar
8 :JarLocation   space\JarLocation_extract.jar
9 :/D:/Temp/JarLocation   space/JarLocation_extract.jar
10 :file:/D:/Temp/JarLocation%20%20%20space/JarLocation_extract.jar
11:D:\Temp\.
12:D:\Temp\JarLocation%20%20%20space
13:D:\Temp\JarLocation   space
14:D:\Temp 

沒有留言:

張貼留言