23

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

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

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

4

4 回答 4

39

如何从Class 文件夹外部读取 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");
于 2012-06-28T19:12:50.037 回答
10

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

        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*/
于 2012-06-28T21:11:05.783 回答
5
Properties property=new Properties();
property.load(new FileInputStream("C:/java/myapp/config.properties"));
于 2017-03-20T09:57:17.337 回答
3

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

您可以从系统属性中获取文件的基本路径,您可以在代码中使用 System.getProperty("basePath") 访问该属性,并且应该将其添加到文件名之前以创建绝对路径。

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

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

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

于 2015-07-18T07:46:58.190 回答