我有如下配置文件“ Replace_IP_List.cfg”
10.19.120.39=[fec0:1111:2222:3333:4444]
[fec0:2222:2222:3333:4444] = 10.18.215.151
我正在读取cfg文件以获取键和值,因为键具有':',所以我无法获取完整的字符串,
Properties prop = new Properties();
InputStream is = new FileInputStream("Replace_IP_List.cfg");
prop.load(is);
Enumeration<?> e = prop.propertyNames();
while (e.hasMoreElements())
{
String key = (String) e.nextElement();
String value = prop.getProperty(key);
System.out.println("Key : " + key + ", Value : " + value);
str=str.replace(key, value);
输出:
Key : 10.19.120.39, Value : [fec0:1111:2222:3333:4444]
Key : [fec0, Value : 2222:2222:3333:4444] = 10.18.215.151
cfg文件是在运行时生成的(或由其他人提供),我不需要编辑cfg文件或转义为:
任何人都可以建议我在程序内部如何逃脱:在读取文件时仅考虑=。预期输出如下,
Key : 10.19.120.39, Value : [fec0:1111:2222:3333:4444]
Key : [fec0:2222:2222:3333:4444], Value : 10.18.215.151
答案 0 :(得分:0)
一种方法可能是克隆您的属性文件,同时在等号之前转义冒号并在如下的帮助器类中读取该属性文件:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.util.Enumeration;
import java.util.Properties;
public class PropertyFileHelper {
class FakeReader extends Reader {
private Reader in;
private File file;
public FakeReader(Reader in) throws IOException {
file = File.createTempFile("dummy", "dummuy");
try(
BufferedReader r = new BufferedReader(in);
BufferedWriter w = new BufferedWriter(new FileWriter(file));
){
String line;
while((line = r.readLine()) != null) {
if(line.contains(":") && line.contains("=") && line.indexOf(':') < line.indexOf('=')){
String modifiedLine = "";
boolean equalFetched = false;
for(char c : line.toCharArray()) {
modifiedLine = modifiedLine.concat(equalFetched ? "" : ( c == ':' ? "\\" : "") + c) ;
equalFetched = c == '=';
}
line = modifiedLine;
}
w.write(line);
w.newLine();
}
}
this.in = new FileReader(file);
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
return in.read(cbuf, off, len);
}
@Override
public void close() throws IOException {
this.in.close();
}
}
private void test() throws IOException {
Properties prop = new Properties();
prop.load(new FakeReader(new FileReader("/home/guest/Desktop/p.properties")));
Enumeration<?> e = prop.propertyNames();
while (e.hasMoreElements())
{
String key = (String) e.nextElement();
String value = prop.getProperty(key);
System.out.println("Key : " + key + " Value : " + value);
}
}
public static void main(String[] args) throws IOException {
new PropertyFileHelper().test();
}
}