我有一个连接到数据库的简单 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/