Search code examples
javafileutils

Merge multiple files recursively using Java


I would like to merge the following .properties files into one. So for example I have structure:

IAS
├── default
│   ├── gateway.properties
│   └── pennytunnelservice.properties
└── FAT
    ├── gateway.properties
    ├── IAS-jer-1
    │   └── gateway.properties
    └── pennytunnelservice.properties

My goal is to have two merged files (in this example) pennytunnelservice.properties nad gateway.properties.

In default/gateway.properties is for example:

abc=$change.me
def=test

In FAT/gateway.properties is for example:

abc=123
ghi=234

In FAT/pennytunnelservice.properties is for example:

mno=text

In FAT/IAS-jer-1/gateway.properties is for example:

xyz=123
ghi=98

And the result should be two files with these rows:

pennytunnelservice.properties

mno=text

gateway.properties

abc=123
def=test
ghi=98
xyz=123

Do you have any idea how to do that?


UPDATED !!!

I have written something like this:

    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;
        }
    });

And the result is

{pennytunnelservice.properties={mno=text}, gateway.properties={abc=123, ghi=234}}

The problem is that files are loaded in the wrong way/order:

IAS/default/pennytunnelservice.properties
IAS/default/gateway.properties
IAS/FAT/IAS-jer-1/gateway.properties
IAS/FAT/pennytunnelservice.properties
IAS/FAT/gateway.properties

It should be:

IAS/default/pennytunnelservice.properties
IAS/default/gateway.properties
IAS/FAT/pennytunnelservice.properties
IAS/FAT/gateway.properties
IAS/FAT/IAS-jer-1/gateway.properties

Solution

  • You need a Map<String, Properties>. is the .properties filename and is the content read from the file.

    Recursively, using a FileVisitor look for property files.

    For each file found, load it updating the old content in the map if the same file name has already been found.

    When all files have been processed iterate over all filenames (keys in map) and for each one save a new properties file with the content gathered from all found files.