[Java] java获取程序运行路径、获取当前jar路径 →→→→→进入此内容的聊天室

来自 , 2021-02-19, 写在 Java, 查看 111 次.
URL http://www.code666.cn/view/350a3797
  1. public class RtuMain {
  2.     public static void main(String[] args) {
  3.         System.out.println(getProjectPath());
  4.         System.out.println(getRealPath());
  5.     }
  6.     public static String getProjectPath() throws UnsupportedEncodingException {
  7.         URL url = RtuMain.class.getProtectionDomain().getCodeSource().getLocation();
  8.         String filePath = URLDecoder.decode(url.getPath(), "utf-8");
  9.         if (filePath.endsWith(".jar")) {
  10.             filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
  11.         }
  12.         File file = new File(filePath);
  13.         filePath = file.getAbsolutePath();
  14.         return filePath;
  15.     }
  16.  
  17.     public static String getRealPath() {
  18.         String realPath = RtuMain.class.getClassLoader().getResource("").getFile();
  19.         File file = new File(realPath);
  20.         realPath = file.getAbsolutePath();
  21.         try {
  22.             realPath = URLDecoder.decode(realPath, "utf-8");
  23.         } catch (Exception e) {
  24.             e.printStackTrace();
  25.         }
  26.         return realPath;
  27.     }
  28. }
  29.  
  30. //java/6265

回复 " java获取程序运行路径、获取当前jar路径"

这儿你可以回复上面这条便签

captcha