最开始我是用这种方式来获取当前 jar 包的文件的:
private static String LOCATION = [MainClass].class.getProtectionDomain()
.getCodeSource().getLocation().getFile();
但是如果路径中包含中文,就会变成带“%xx%xx”格式的字符串。所以应该这样写才对:
private static String LOCATION;
static {
try {
LOCATION = URLDecoder.decode([MainClass].class.getProtectionDomain()
.getCodeSource().getLocation().getFile(), “UTF-8″);
} catch (UnsupportedEncodingException e) {
LOCATION = “”;
}
}
对于Java程序,无论是未打包Class的还是打包的JAR都有效。
public class MyPath { public static String getProjectPath() { java.net.URL url = MyPath.class.getProtectionDomain().getCodeSource().getLocation(); String filePath = null; try { filePath = java.net.URLDecoder.decode(url.getPath(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } if (filePath.endsWith(".jar")) filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1); java.io.File file = new java.io.File(filePath); filePath = file.getAbsolutePath(); return filePath; } public static String getRealPath() { String realPath = MyPath.class.getClassLoader().getResource("").getFile(); java.io.File file = new java.io.File(realPath); realPath = file.getAbsolutePath(); try { realPath = java.net.URLDecoder.decode(realPath, "utf-8"); } catch (Exception e) { e.printStackTrace(); } |