java-读取jar文件之外的属性文件

标签 java

我有一个连接到数据库的简单 Java 程序。连接在 db.properties 文件中配置。我的程序运行良好。

当我想将其编译为可执行 jar 文件时,我会将属性文件放在同一文件夹中,以便用户可以轻松编辑属性文件并根据自己的喜好更改连接设置。这里的小问题是我的dbpath,我必须指定确切的目录来读取属性文件。

我想知道是否可以将其保存在同一文件夹中并将路径设置为当前目录,这样无论用户将文件夹保存在何处,它始终能够读取数据库属性,而无需对路径进行硬编码。

代码:

 Properties props=new Properties();
                String dbpath = "C:\\Users\\nickywan123\\Documents\\db.properties";
                FileInputStream in = new FileInputStream(dbpath);

             props.load(in);
             in.close();

             String driver = props.getProperty("jdbc.driver");
             if(driver!=null){
              Class.forName(driver);

                }

                String url=props.getProperty("jdbc.url");
                String username=props.getProperty("jdbc.username");
                String password=props.getProperty("jdbc.password");

                Connection con = DriverManager.getConnection(url,username,password);

我尝试了不同的解决方案来获取 jar 文件的位置,例如 Get location of JAR file 但它不会返回我希望能够读取它的位置。

我很感激任何建议

最佳答案

I will place the properties file in the same folder so user can easily edit the properties file and change the connection settings to their liking

您面临的问题归结为以下事实:运行应用程序的工作目录可能与存储应用程序及其文件的位置不同。您不能依赖已修复的位置。

相反,您应该采用平台的约定并将文件存储在“通用”位置(这是固定的)。

在 Windows 上可能...

System.getProperty("user.dir") + "/AppData/{App name}/{folder name}/{file}"

在 MacOS 上可能是...

System.getProperty("user.dir") + "/Library/Application Support/{App name}/{folder name}/{file}"

在 Linux 上可能是......

System.getProperty("user.dir") + ".{Appname}/{folder name}/file"

What about this, the jar file and properties file should be in the same FOLDER. Then user can decide where they want to store/keep the folder, which is the best solution to this?

没关系,您仍然面临“工作目录”与“安装目录”不同的风险,这就是开发上述解决方案的“原因” - 这不仅仅是一个 Java 问题,而是影响所有节目

您还可能遇到操作系统权限问题...看看您的 Windows 😠

“另一个”解决方案是允许用户通过命令行传入文件/位置,允许他们从任何地方运行 Jar,同时允许他们指定他们想要使用的属性文件的位置......这意味着他们可以根据需要拥有不止一个

关于java-读取jar文件之外的属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53405312/

相关文章:

java - 是什么阻止您在包中声明其他类,从而使您无法访问包私有(private)成员

java - 什么进入 Spring Security 的 ACL_OBJECT_IDENTITY 表?

java - Android 图像按钮 fragment

java - 使用服务方法调用 servlet 的 init 和 destroy 方法

java - 修昔底德:从头开始安装原型(prototype) - 跳过所有测试

java - AppEngine 中的 JDO : keep the original entity when deleting from unowned relationship

java - 在 Linux 上调用 JNI 代码时奇怪的崩溃;我是否正确编译了我的共享库?

Java:某处是否还有另一种链表?

java - 使用流,如何映射 HashMap 中的值?

Java 应用程序部署/安装程序选项?