首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >读取不转义值的Java属性文件

读取不转义值的Java属性文件
EN

Stack Overflow用户
提问于 2011-06-04 07:15:22
回答 8查看 20.2K关注 0票数 20

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

Problem

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

代码语言:javascript
复制
dir = c:\\mydir

需要

我需要一些方法来接受其中的值没有转义的属性文件,以便用户可以指定:

代码语言:javascript
复制
dir = c:\mydir
EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2011-06-12 18:14:11

为什么不简单地扩展属性类以包含双正斜杠的剥离。这样做的一个好特性是,在程序的其余部分中,您仍然可以使用原始的Properties类。

代码语言:javascript
复制
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);
    }
}

使用新类很简单,如下所示:

代码语言:javascript
复制
PropertiesEx p = new PropertiesEx();
p.load(new FileInputStream("C:\\temp\\demo.properties"));
p.list(System.out);

剥离代码也可以改进,但一般原则是存在的。

票数 22
EN

Stack Overflow用户

发布于 2011-06-04 07:27:49

有两个选项:

  • 使用XML properties格式代替
  • 编写器针对修改后的.properties格式编写您自己的解析器,但不会转义
票数 7
EN

Stack Overflow用户

发布于 2011-06-09 05:14:35

您可以在加载属性之前对文件进行“预处理”,例如:

代码语言:javascript
复制
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());
}

你的代码可能是这样的

代码语言:javascript
复制
Properties properties = new Properties();
properties.load(preprocessPropertiesFile("path/myfile.properties"));

这样做,您的.properties文件看起来就像您所需要的,但是您将拥有可供使用的属性值。

*我知道应该有更好的方法来操作文件,但我希望这会有所帮助。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6233532

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档