读取 Java 属性文件而不转义值 [英] Reading Java Properties file without escaping values

查看:13
本文介绍了读取 Java 属性文件而不转义值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序需要使用 .properties 文件进行配置.在属性文件中,允许用户指定路径.

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

问题

属性文件需要转义值,例如

Properties files need values to be escaped, eg

dir = c:\mydir

需要

我需要某种方式来接受值未转义的属性文件,以便用户可以指定:

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

dir = c:mydir

推荐答案

为什么不简单地扩展属性类以合并去除双正斜杠.这样做的一个好处是,通过程序的其余部分,您仍然可以使用原始的 Properties 类.

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("
".getBytes());
        }

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

使用新类很简单:

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.

这篇关于读取 Java 属性文件而不转义值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆