Hunter0x7c7
2023-08-11 03b69d0e3c9e8b1c1c5f0e473273f2e975186ea1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.github.hunter0x7c7.sync.utils;
 
import java.io.File;
import java.net.URL;
 
public class PathUtil {
    /**
     * 如果没打包后运行则debug为true
     */
    public static boolean debug = false;
    /**
     * 项目所在路径
     */
    public static final String projectPath = initProjectPathAndDebug();
 
    /***
     * 获取项目根路径,无论是打包成jar文件。
     * 为了保证调试时获取项目路径,而不是bin路径,增加逻辑: 如果以bin目录接,则返回上一层目录
     * 例如:F:\eclipse\work\JavaFX\PersonalAssistant  后面的bin目录会去掉
     * @return 例如:F:\eclipse\work\JavaFX\AddressApp\build\dist
     */
    private static String initProjectPathAndDebug() {
 
        if (SystemUtil.isWindows()) {
            System.out.println(".....isWindows....");
        }
        if (SystemUtil.isMacOs()) {
            System.out.println("....isMacOs.....");
        }
        if (SystemUtil.isLinux()) {
            System.out.println("......isLinux...");
        }
 
 
        URL url = PathUtil.class.getProtectionDomain().getCodeSource().getLocation();
        String filePath = null;
        try {
            filePath = java.net.URLDecoder.decode(url.getPath(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (filePath != null) {
            if (filePath.endsWith(".jar")
                    || filePath.endsWith(".exe")
                    || filePath.endsWith(".dmg")
                    || filePath.endsWith(".tar")
                    || filePath.endsWith(".zip")) {
                filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
            }
            //如果以bin目录接,则说明是开发过程debug测试查询,返回上一层目录
            if (filePath.endsWith("bin/") || filePath.endsWith("bin\\")) {
                debug = true;
                filePath = filePath.substring(0, filePath.lastIndexOf("bin"));
            }
        }
        if (filePath != null) {
            return new File(filePath).getAbsolutePath();
        }
        return null;
    }
 
    /***
     * 这个方法打包位jar文件就无法获取项目路径了。
     * @return
     */
    public static String getRealPath() {
        String realPath = PathUtil.class.getClassLoader().getResource("").getFile();
        File file = new File(realPath);
        realPath = file.getAbsolutePath();//去掉了最前面的斜杠/
        try {
            realPath = java.net.URLDecoder.decode(realPath, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return realPath;
    }
 
}