【问题标题】:how to read a file from resources folder in properties file如何从属性文件中的资源文件夹中读取文件
【发布时间】:2018-11-02 15:58:06
【问题描述】:

我在资源文件夹src/test/resources/file.xml 下有一个文件 另一个在src/test/resources/test.properties 下。我想在属性文件中设置一个属性指向file.xml。我怎样才能做到这一点?

假设我有财产

test.file = file.xml

我的java类读取文件如下:

File cert = new File(fileName); // fileName is the value of test.file

但这不起作用。

【问题讨论】:

  • 不太清楚问题是什么。你遇到了什么错误?
  • 您需要完整路径或URI 实例来创建File 的实例。
  • @question_tech 您需要使用相对路径来获取全名。请检查我的答案

标签: java spring-mvc properties-file


【解决方案1】:

您可以使用Properties 类来读取和写入配置文件。

【讨论】:

    【解决方案2】:
    • 首先,您需要找到资源的相对路径使用 以下步骤
    • 其次,可以配置和加载测试属性文件
    • 最后,读取属性值并附加资源
      目录

    代码:

    String rootDirectory=System.getProperty("user.dir");
    String resourceDirectory=rootDirectory+"src/test/resources/";
    
    //Configure property File
    Properties properties = new Properties();
    properties.load(new FileInputStream(resourceDirectory+"test.properties"));
    PropertyConfigurator.configure(properties);
    
    //To get the property value
    String tempFileName=properties.getProperty("test.file");
    
    //filename Needs to be changed as below
    File cert = new File(resourceDirectory+tempFileName);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-05
      • 2017-05-18
      • 2018-11-12
      • 1970-01-01
      • 2016-03-17
      • 2017-11-08
      • 2020-01-20
      相关资源
      最近更新 更多