【发布时间】:2018-01-23 08:38:47
【问题描述】:
我想将以下 .properties 文件合并为一个。所以例如我有结构:
IAS
├── default
│ ├── gateway.properties
│ └── pennytunnelservice.properties
└── FAT
├── gateway.properties
├── IAS-jer-1
│ └── gateway.properties
└── pennytunnelservice.properties
我的目标是合并两个文件(在本例中)pennytunnelservice.properties nad gateway.properties。
在default/gateway.properties中例如是:
abc=$change.me
def=test
在FAT/gateway.properties中例如是:
abc=123
ghi=234
在FAT/pennytunnelservice.properties中例如是:
mno=text
在 FAT/IAS-jer-1/gateway.properties 中例如:
xyz=123
ghi=98
结果应该是包含这些行的两个文件:
pennytunnelservice.properties
mno=text
gateway.properties
abc=123
def=test
ghi=98
xyz=123
你知道怎么做吗?
已更新!!!
我写过这样的:
public static void main(String[] args) throws IOException {
String dirName = "/IAS";
File file = new File(dirName);
Map<String,Properties> files = new HashMap<>();
Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
System.out.println(file);
Properties prop = new Properties();
FileInputStream input = new FileInputStream(file.toString());
prop.load(input);
files.put(file.getFileName().toString(), prop);
return FileVisitResult.CONTINUE;
}
});
结果是
{pennytunnelservice.properties={mno=text}, gateway.properties={abc=123, ghi=234}}
问题在于文件以错误的方式/顺序加载:
IAS/default/pennytunnelservice.properties
IAS/default/gateway.properties
IAS/FAT/IAS-jer-1/gateway.properties
IAS/FAT/pennytunnelservice.properties
IAS/FAT/gateway.properties
应该是:
IAS/default/pennytunnelservice.properties
IAS/default/gateway.properties
IAS/FAT/pennytunnelservice.properties
IAS/FAT/gateway.properties
IAS/FAT/IAS-jer-1/gateway.properties
【问题讨论】:
-
我建议采用以下方法。将单独的 List
一个用于 gateway.properties,另一个用于 pennytunnelservice.properties。解析每个文件并将其添加到正确的 List 。最后,继续将这些属性列表添加到单个属性对象中。然后遍历最终的 Properties 对象并提取键值对并写入文件。 -
看看这里,你可能会知道怎么做:stackoverflow.com/questions/2004833/…。你需要做的是用你的文件内容加载每个
Properties -
来自Javadoc“文件树遍历depth-first”,所以你需要将
Paths存储在Collection中并排序,然后处理文件。 -
@VenkataRaju 谢谢,这是一个很好的观点。