【问题标题】:Merge multiple files recursively using Java使用Java递归合并多个文件
【发布时间】: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 谢谢,这是一个很好的观点。

标签: java fileutils


【解决方案1】:

您需要Map&lt;String, Properties&gt;。是 .properties 文件名,是从文件中读取的内容。

递归地,使用FileVisitor 查找属性文件。

对于找到的每个文件,如果已找到相同的文件名,则加载它以更新地图中的旧内容。

处理完所有文件后,遍历所有文件名(映射中的键),并为每个文件保存一个新的属性文件,其中包含从所有找到的文件中收集的内容。

【讨论】:

  • 谢谢,你能检查一下我上次的编辑吗?我尝试实施一种解决方案,但有问题 - 文件以错误的方式/顺序加载。你能给我一个小提示吗?
  • @sipekmichal.cz:顺序由图遍历算法给出。您必须创建另一个 FileVisitor(可能从 SimpleFileVisitor 派生)以您想要的方式处理订单(按字母顺序,不区分大小写,...)。在您的情况下,您似乎想最后处理目录。
猜你喜欢
  • 2017-07-20
  • 2020-09-06
  • 2011-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-24
相关资源
最近更新 更多