Reading Java Properties file without escaping values

pdeva picture pdeva · Jun 4, 2011 · Viewed 19.6k times · Source

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

Problem

Properties files need values to be escaped, eg

dir = c:\\mydir

Needed

I need some way to accept a properties file where the values are not escaped, so that the users can specify:

dir = c:\mydir

Answer

Ian Harrigan picture Ian Harrigan · Jun 12, 2011

Why not simply extend the properties class to incorporate stripping of double forward slashes. A good feature of this will be that through the rest of your program you can still use the original Properties class.

public class PropertiesEx extends Properties {
    public void load(FileInputStream fis) throws IOException {
        Scanner in = new Scanner(fis);
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        while(in.hasNext()) {
            out.write(in.nextLine().replace("\\","\\\\").getBytes());
            out.write("\n".getBytes());
        }

        InputStream is = new ByteArrayInputStream(out.toByteArray());
        super.load(is);
    }
}

Using the new class is a simple as:

PropertiesEx p = new PropertiesEx();
p.load(new FileInputStream("C:\\temp\\demo.properties"));
p.list(System.out);

The stripping code could also be improved upon but the general principle is there.