我的应用程序需要使用.properties文件进行配置。在属性文件中,允许用户指定路径。
Problem
属性文件需要转义值,例如
dir = c:\\mydir
需要
我需要一些方法来接受其中的值没有转义的属性文件,以便用户可以指定:
dir = c:\mydir
发布于 2011-06-12 18:14:11
为什么不简单地扩展属性类以包含双正斜杠的剥离。这样做的一个好特性是,在程序的其余部分中,您仍然可以使用原始的Properties
类。
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);
}
}
使用新类很简单,如下所示:
PropertiesEx p = new PropertiesEx();
p.load(new FileInputStream("C:\\temp\\demo.properties"));
p.list(System.out);
剥离代码也可以改进,但一般原则是存在的。
发布于 2011-06-04 07:27:49
有两个选项:
发布于 2011-06-09 05:14:35
您可以在加载属性之前对文件进行“预处理”,例如:
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());
}
你的代码可能是这样的
Properties properties = new Properties();
properties.load(preprocessPropertiesFile("path/myfile.properties"));
这样做,您的.properties文件看起来就像您所需要的,但是您将拥有可供使用的属性值。
*我知道应该有更好的方法来操作文件,但我希望这会有所帮助。
https://stackoverflow.com/questions/6233532
复制相似问题