回答編集履歴

3

別の方法を追記した。

2015/11/20 10:21

投稿

eripong
eripong

スコア1546

test CHANGED
@@ -27,3 +27,27 @@
27
27
  System.out.println(canonicalFile.getParent());
28
28
 
29
29
  ```
30
+
31
+
32
+
33
+
34
+
35
+ ### 別の方法
36
+
37
+ 以下の方法でも、jarの場所を取得できるはずです。
38
+
39
+ file:/tmp/sample.jar!/example/MyClass.class
40
+
41
+ のような形で取得できるので、:から!までを切り出せばよいです。
42
+
43
+
44
+
45
+ ```lang-java
46
+
47
+ URL resourceJarUrl = MyClass.class.getResource("MyClass.class");
48
+
49
+ String resourceJarPath = resourceJarUrl.getFile();
50
+
51
+ resourceJarPath = URLDecoder.decode(resourceJarPath, "UTF-8");
52
+
53
+ ```

2

複数行で実行するように修正した。

2015/11/20 10:21

投稿

eripong
eripong

スコア1546

test CHANGED
@@ -10,8 +10,20 @@
10
10
 
11
11
  ```lang-java
12
12
 
13
- File file = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
13
+ ProtectionDomain protectionDomain = MyClass.class.getProtectionDomain();
14
14
 
15
+ CodeSource codeSource = protectionDomain.getCodeSource();
16
+
17
+ URL location = codeSource.getLocation();
18
+
19
+ URI uri = location.toURI();
20
+
21
+ File file = new File(uri.getPath());
22
+
23
+
24
+
25
+ File canonicalFile = file.getCanonicalFile();
26
+
15
- System.out.println(file.getCanonicalFile().getParent());
27
+ System.out.println(canonicalFile.getParent());
16
28
 
17
29
  ```

1

ディレクトリを取得するコードに修正した。

2015/11/20 10:09

投稿

eripong
eripong

スコア1546

test CHANGED
@@ -12,6 +12,6 @@
12
12
 
13
13
  File file = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
14
14
 
15
- System.out.println(file.getCanonicalPath());
15
+ System.out.println(file.getCanonicalFile().getParent());
16
16
 
17
17
  ```