使用Java递归合并多个文件
我想将以下.properties文件合并为一个文件。例如,我有一个结构:使用Java递归合并多个文件,java,fileutils,Java,Fileutils,我想将以下.properties文件合并为一个文件。例如,我有一个结构: IAS ├── default │ ├── gateway.properties │ └── pennytunnelservice.properties └── FAT ├── gateway.properties ├── IAS-jer-1 │ └── gateway.properties └── pennytunnelservice.properties 我的目标是有两个合
IAS
├── default
│ ├── gateway.properties
│ └── pennytunnelservice.properties
└── FAT
├── gateway.properties
├── IAS-jer-1
│ └── gateway.properties
└── pennytunnelservice.properties
我的目标是有两个合并文件(在本例中)pennytunnelservice.properties和gateway.properties
在默认/gateway.properties中,例如:
abc=$change.me
def=test
abc=123
ghi=234
mno=text
xyz=123
ghi=98
在FAT/gateway中,属性是例如:
abc=$change.me
def=test
abc=123
ghi=234
mno=text
xyz=123
ghi=98
在FAT/PennyTunnelsService.properties中,例如:
abc=$change.me
def=test
abc=123
ghi=234
mno=text
xyz=123
ghi=98
在FAT/IAS-jer-1/gateway中。属性例如:
abc=$change.me
def=test
abc=123
ghi=234
mno=text
xyz=123
ghi=98
结果应该是两个包含以下行的文件:
pennytunnelservice.properties
mno=text
abc=123
def=test
ghi=98
xyz=123
gateway.properties
mno=text
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;
}
});
问题是文件加载的方式/顺序错误:
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
你需要一张地图
。是.properties文件名,是从文件中读取的内容
递归地,使用查找属性文件
对于找到的每个文件,如果已经找到相同的文件名,则加载该文件并更新映射中的旧内容
处理完所有文件后,迭代所有文件名(映射中的键),并为每个文件保存一个新的属性文件,其中包含从所有找到的文件中收集的内容 我建议采取以下方法。分别列出gateway.properties和pennytunnelservice.properties。解析每个文件并将它们添加到正确的列表中。最后,继续将这些属性列表添加到单个属性对象中。然后迭代最后一个属性对象,提取键值对并写入文件。您需要做的是从Javadoc“文件树被遍历”中加载每个
属性和文件内容,因此您需要将路径
存储在集合中
并排序,然后处理文件。@VenkataRaju谢谢,这是一个很好的观点。谢谢,您能检查我上次的编辑吗?我试图实现一个解决方案,但遇到了问题-文件以错误的方式/顺序加载。你能给我一个小提示吗?@sipekmichal.cz:通过图遍历算法,顺序是givn。您必须创建另一个FileVisitor(可能来自SimpleFileVisitor),以您想要的方式(按字母顺序,不区分大小写,…)处理顺序。在您的情况下,似乎希望最后处理目录。有关更多详细信息,请参阅此: