【问题标题】:Access file adjacent to jar file访问jar文件旁边的文件
【发布时间】:2011-11-08 09:35:53
【问题描述】:

如何以最简洁的方式访问与 jar 文件(不在其中)相邻的文件?

我尝试了各种组合,例如 File configFile = new File("..//pinger.properties");Pinger.class.getResourceAsStream("pinger.properties");,但没有读取文件。

谢谢!

【问题讨论】:

    标签: java file io


    【解决方案1】:

    您可以尝试使用java.util.Properties 类。

       Properties properties = new Properties();
       properties.load(getClass().getClassLoader().getResourceAsStream("pinger.properties"));
    

    另一个示例是here

    【讨论】:

      【解决方案2】:

      如何以最简洁的方式访问与 jar 文件(不在其中)相邻的文件?

      添加一个使用相对路径1引用依赖 Jar 的清单文件。然后使用getResource(String) 获取资源的URL

      1. 详情请见Adding Classes to the JAR File's Classpath

      【讨论】:

        【解决方案3】:

        获取 jar 文件的位置

        考虑以下函数

        public String path(String filename)
        {
        URL url1 = getClass().getResource("");
        String ur=url1.toString();
        ur=ur.substring(9);
        String truepath[]=ur.split("myjar.jar!");
        truepath[0]=truepath[0].replaceAll("%20"," ");
        return truepath[0]+filename;
        }//This method will work on Windows and Linux as well.
        //You can alternatively use the following line to get the path of your jar file
        //classname.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        

        假设你的 jar 文件在 D:\Test\dist

        然后 path() 将返回 /D:/Test/dist/filename

        【讨论】:

          猜你喜欢
          • 2011-07-07
          • 2012-01-05
          • 1970-01-01
          • 2011-07-26
          • 1970-01-01
          • 2013-12-13
          • 2011-08-12
          • 2015-09-19
          • 1970-01-01
          相关资源
          最近更新 更多