package com.github.hunter0x7c7.sync.utils; import java.io.File; import java.net.URL; import java.net.URLDecoder; public class PathUtil { /** * 如果没打包后运行则debug为true */ public static boolean debug = false; /** * 项目所在路径 */ public static final String projectPath = initProjectPathAndDebug(); public static String getConfigFilePath(String cfgName) { return String.format("%s%s%s", projectPath, getFileSeparator(), cfgName); } /*** * 获取项目根路径,无论是打包成jar文件。 * 为了保证调试时获取项目路径,而不是bin路径,增加逻辑: 如果以bin目录接,则返回上一层目录 * 例如:F:\eclipse\work\JavaFX\PersonalAssistant 后面的bin目录会去掉 * @return 例如:F:\eclipse\work\JavaFX\AddressApp\build\dist */ private static String initProjectPathAndDebug() { URL url = PathUtil.class.getProtectionDomain().getCodeSource().getLocation(); String filePath = null; try { filePath = 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; } public static String getFileSeparator() { return File.separator; } /*** * 这个方法打包位jar文件就无法获取项目路径了。 * @return */ public static String getRealPath() { String realPath = PathUtil.class.getClassLoader().getResource("").getFile(); File file = new File(realPath); realPath = file.getAbsolutePath();//去掉了最前面的斜杠/ try { realPath = URLDecoder.decode(realPath, "utf-8"); } catch (Exception e) { e.printStackTrace(); } return realPath; } }