Reading Java Properties file without escaping values

前端 未结 8 1770
滥情空心
滥情空心 2020-12-06 09:54

My application needs to use a .properties file for configuration. In the properties files, users are allow to specify paths.

Problem

Propert

8条回答
  •  离开以前
    2020-12-06 10:15

    You can "preprocess" the file before loading the properties, for example:

    public InputStream preprocessPropertiesFile(String myFile) throws IOException{
        Scanner in = new Scanner(new FileReader(myFile));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        while(in.hasNext())
            out.write(in.nextLine().replace("\\","\\\\").getBytes());
        return new ByteArrayInputStream(out.toByteArray());
    }
    

    And your code could look this way

    Properties properties = new Properties();
    properties.load(preprocessPropertiesFile("path/myfile.properties"));
    

    Doing this, your .properties file would look like you need, but you will have the properties values ready to use.

    *I know there should be better ways to manipulate files, but I hope this helps.

提交回复
热议问题