主类的路径结构如下:
D:/java/myapp/src/manClass.java
我想把属性文件放进去
D:/java/myapp/config.properties
其中将包含一个文件名和一些其他配置。我将在属性文件中设置文件名,如下所示:file=file_to_read.txt
这个 file_to_read.txt
将位于 D:/java/myapp/folder_of_file/
主类会先从属性文件中读取文件名,然后再从文件中获取内容。
如果 config.properties
和 file_to_read.txt
都在 src/
中,并且 mainClass.java
。但无法以我想要的方式成功。
谁能帮我解决这个问题?如果我想将 myapp
文件夹放在驱动器中的任何位置,并且内部结构与上面描述的相同并且程序将正确完成工作,我需要您的建议。
我还需要您的建议,如果我想从构建项目后创建的 jar 中完成这项工作,那么我可以毫无问题地做到这一点吗?
我已经尝试如下只是为了读取属性文件:
URL location = myClass.class.getProtectionDomain().getCodeSource().getLocation();
String filePath = location.getPath().substring(1,location.getPath().length());
InputStream in = myClass.class.getResourceAsStream(filePath + "config.properties");
prop.load(in);
in.close();
System.out.println(prop.getProperty("file"));
但是当试图从属性文件中获取属性时,这会出错。 谢谢!
最佳答案
How to read a properties file in java from outside the Class folder?
使用带有固定磁盘文件系统路径的FileInputStream
。
InputStream input = new FileInputStream("D:/java/myapp/config.properties");
更好的方法是将其移动到类路径覆盖的现有路径之一,或者将其原始路径 D:/java/myapp/
添加到类路径中。然后就可以得到如下:
InputStream input = getClass().getResourceAsStream("/config.properties");
或
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties");
关于java - 如何从 Class 文件夹外部读取 java 中的属性文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11251289/