如何使用maven插件合并具有相同名称的不同文件夹下的文件

时间:2015-01-07 01:57:19

标签: maven

我需要在两个不同的文件夹下合并所有具有相同名称的文件,并将其输出到另一个文件夹。

例如:

common
     |
     V1.sql
     V2.sql
module
     |
     V1.sql
     V2.sql

现在我的目标目录应该是

target dir
        |
        V1.sql(has both the contents of common and module)
        V2.sql(has both the contents of common and module)

我看过几个maven插件,但他们似乎不支持这个。如果有人遇到过这样的问题或实施插件,请指导,

1 个答案:

答案 0 :(得分:0)

不太漂亮,但是我使用maven exec插件实现了这一点:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.4.0</version>
    <executions>
        <execution>
            <id>resourceMerge</id>
            <goals>
                <goal>java</goal>
            </goals>
            <phase>prepare-package</phase>
            <configuration>
                <mainClass>mavenProcessor.Resourcesmerger</mainClass>
                <arguments>
                    <argument>${project.build.directory}/resourcesDefault</argument>
                    <argument>${project.build.directory}/resourcesProfile</argument>
                    <argument>${project.build.directory}/resourcesMerged</argument>
                </arguments>
            </configuration>
        </execution>
    </executions>
</plugin>

处理器看起来像这样

package mavenProcessor;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;

public class Resourcesmerger {


    public static void main(String[] args) throws Throwable {

        Path inputDir1 = new File(args[0]).toPath();
        Path inputDir2 = new File(args[1]).toPath();
        Path outputDir = new File(args[2]).toPath();

        copyAppending(inputDir1, outputDir);

        if (Files.exists(inputDir2)) {
            copyAppending(inputDir2, outputDir);
        }

    }

    private static void copyAppending(Path inputDir1, Path outputDir) throws IOException, FileNotFoundException {
        List<Path> defaultResources = Files.walk(inputDir1).collect(Collectors.toList());
        for (Path path : defaultResources) {
            if (Files.isRegularFile(path)) {
                Path relativePath = inputDir1.relativize(path);
                Path targetPath = outputDir.resolve(relativePath);
                targetPath.getParent().toFile().mkdirs();
                try (FileOutputStream fos = new FileOutputStream(targetPath.toFile(), true)) {
                    System.out.println("Merge " + path + " to " + targetPath);
                    System.out.flush();
                    Files.copy(path, fos);
                }
            }
        }
    }
}