如何从Class文件夹外部读取java中的属性文件?

时间:2012-06-28 19:07:59

标签: java file file-io properties

我对主类有以下路径结构:

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.propertiesfile_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"));

但是当尝试从属性文件中获取getProperty时,这会给出错误。 谢谢!

4 个答案:

答案 0 :(得分:30)

  

如何从在类文件夹外中读取java中的属性文件?

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");

答案 1 :(得分:7)

感谢大家的建议。我通过这种方式完成了这项工作:

        Properties prop = new Properties();
        String dir = System.getProperty("user.dir");
        InputStream in = new FileInputStream(dir + "/myapp/config.properties");
        prop.load(in);
        in.close();
        String filePath = dir + "/myapp/folder_of_file/" + prop.getProperty("file"); /*file contains the file name to read*/

答案 2 :(得分:3)

Properties property=new Properties();
property.load(new FileInputStream("C:/java/myapp/config.properties"));

答案 3 :(得分:1)

您需要指定绝对路径,但您不应该对其进行硬编码,因为这会使开发和生产环境等之间的切换变得更加困难。

您可以从System属性中获取文件的基本路径,您可以在代码中使用System.getProperty(" basePath")访问该文件,并且应该在您的文件名前加上创造一条绝对的道路。

在运行应用程序时,您可以在java命令行中指定路径,如下所示:

java -DbasePath="/a/b/c" ...

...表示运行程序的Java命令的当前参数。