Java 如何将目录(不包括父目录)的所有内容移动到Groovy的另一个目录

Java 如何将目录(不包括父目录)的所有内容移动到Groovy的另一个目录,java,groovy,Java,Groovy,我有一个groovy脚本,它接收2个zip文件,解压它们,然后处理它们 我遇到的问题是,当我去解压zip文件时,每个解压文件都会生成一个子文件夹,然后是解压文件的内容,而不是内容本身 例如: 当前,当我解压缩时会发生这种情况 content-1232.zip->/content-1232/content/ 我想要的是 content-1232.zip->/content-1232/ 或 放入新目录 content-1232.zip->/new\u目录/ 我试过了,但没用: Path basePa

我有一个groovy脚本,它接收2个zip文件,解压它们,然后处理它们

我遇到的问题是,当我去解压zip文件时,每个解压文件都会生成一个子文件夹,然后是解压文件的内容,而不是内容本身

例如:

当前,当我解压缩时会发生这种情况

content-1232.zip->/content-1232/content/

我想要的是

content-1232.zip->/content-1232/

放入新目录

content-1232.zip->/new\u目录/

我试过了,但没用:

Path basePath = Paths.get(output.getAbsolutePath())
Path srcPath = Paths.get(pdfContent.getAbsolutePath())
Path targetPath = basePath

Files.move(srcPath, targetPath.resolve(basePath.relativize(srcPath)))
这似乎是一件很简单的事情,但我没有任何运气。如何在groovy中实现这一点?任何帮助都将不胜感激

编辑:

static void main(String[] args) {
    logger.info("Beginning unpacking of content...")


    def output = new File("/Users/Haddad/Desktop/workspace/c")
    def pdfContent = new File("/Users/Haddad/Desktop/workspace/c/pdf-content")


    // Look for test1 and test2 production content zip file, ensure there's only 1 and unzip
    List appZip = FileUtil.discoverFiles(output, true, "test1-production-content-.*\\.zip")
    List compliZip = FileUtil.discoverFiles(output,true,"test2-production-content-.*\\.zip")

    assert appZip.size() == 1, "Did not find expected number of test1 content zip, actual size is: " + appZip.size()
    assert compliZip.size() == 1, "Did not find expected number of test2 content zip, actual size is " + appZip.size()

    def outputAppZip = new File(output.getAbsolutePath()+"/"+appZip.get(0).getName()+"-intermediate");
    def outputCompliZip = new File(output.getAbsolutePath()+"/"+compliZip.get(0).getName()+"-intermediate");

    ZipUtil.unzipToDisk(appZip.get(0), outputAppZip )
    ZipUtil.unzipToDisk(compliZip.get(0), outputCompliZip )


    // move it to pdf content
    List applicationContent = FileUtil.discoverDirectories(output, "one-production-content-.*-intermediate", true)
    assert applicationContent.size() == 1, "Did not find expected number of test1 contents " + applicationContent.size()

    def success = FileUtil.copy(applicationContent.get(0), pdfContent)
    assert success, "Could not copy tt content"

    // move pdf content
    List complianceContent = FileUtil.discoverDirectories(output, "two-production-content-.*-intermediate", true)
    assert complianceContent.size() == 1, "Did not find expected number of test2 contents " + complianceContent.size()
    success = FileUtil.copy(complianceContent.get(0), pdfContent)
    assert success, "Could not copy pdf content"

    // rename to not be unsupported
    List unsupportedDirs = FileUtil.discoverDirectories(pdfContent, "_unsupported_.*", true)
    for (File file : unsupportedDirs) {
        file.renameTo(new File(file.getParentFile(), file.getName().replace("_unsupported_", "")))
    }


    logger.info("Completed!")
}
这个怎么样

输入

test.zip
--- test
------ test.txt
<someFolder>
--- test.txt
public class Main {

    public static void main(String[] args) throws IOException {
        Main main = new Main();

        Path input = main.getInputPath(args);
        Path output = main.getOutputPath(args);

        main.extract(input, output);
        main.flatten(output);
    }

    private final Path getInputPath(String[] args) {
        if (args.length < 1) {
            throw new IllegalArgumentException("Usage: Main <inputFile> [<outputDirectory>]");
        }

        Path input = Paths.get(args[0]);

        if (!isRegularFile(input)) {
            throw new IllegalArgumentException(String.format("%s is not a file.", input.toFile().getAbsolutePath()));
        }

        return input;
    }

    private final Path getOutputPath(String[] args) throws IOException {
        return args.length < 2 ? Files.createTempDirectory(null) :
                Files.createDirectories(Paths.get(args[1]));
    }

    private final void extract(Path input, Path output) throws IOException {
        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(input.toFile()))) {
            for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) {
                String fileName = ze.getName();

                if (fileName.contains("__MACOSX")) {
                    continue;
                }

                File file = new File(output.toFile(), fileName);

                if (ze.isDirectory()) {
                    Files.createDirectories(file.toPath());
                    continue;
                }

                System.out.println("Extracting: " + file.getAbsolutePath());

                try (FileOutputStream fos = new FileOutputStream(file, true)) {
                    byte[] buffer = new byte[4096];
                    for (int len = zis.read(buffer); len > 0; len = zis.read(buffer)) {
                        fos.write(buffer, 0, len);
                    }
                }
            }
        }
    }

    private final void flatten(Path output) throws IOException {
        List<Path> children = Files.list(output)
                .collect(toList());

        if (children.size() == 1) {
            Path path = children.get(0);
            Files.list(path)
                    .forEach(f -> {
                        try {
                            System.out.printf("Moving %s to %s.\n", f.toFile().getAbsolutePath(),
                                    output.toFile().getAbsolutePath());
                            Files.move(f, Paths.get(output.toFile().getAbsolutePath(), f.toFile().getName()));
                        } catch (IOException e) {
                            throw new UncheckedIOException(e);
                        }
                    });

            Files.delete(path);
        }
    }
}
输出

test.zip
--- test
------ test.txt
<someFolder>
--- test.txt
public class Main {

    public static void main(String[] args) throws IOException {
        Main main = new Main();

        Path input = main.getInputPath(args);
        Path output = main.getOutputPath(args);

        main.extract(input, output);
        main.flatten(output);
    }

    private final Path getInputPath(String[] args) {
        if (args.length < 1) {
            throw new IllegalArgumentException("Usage: Main <inputFile> [<outputDirectory>]");
        }

        Path input = Paths.get(args[0]);

        if (!isRegularFile(input)) {
            throw new IllegalArgumentException(String.format("%s is not a file.", input.toFile().getAbsolutePath()));
        }

        return input;
    }

    private final Path getOutputPath(String[] args) throws IOException {
        return args.length < 2 ? Files.createTempDirectory(null) :
                Files.createDirectories(Paths.get(args[1]));
    }

    private final void extract(Path input, Path output) throws IOException {
        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(input.toFile()))) {
            for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) {
                String fileName = ze.getName();

                if (fileName.contains("__MACOSX")) {
                    continue;
                }

                File file = new File(output.toFile(), fileName);

                if (ze.isDirectory()) {
                    Files.createDirectories(file.toPath());
                    continue;
                }

                System.out.println("Extracting: " + file.getAbsolutePath());

                try (FileOutputStream fos = new FileOutputStream(file, true)) {
                    byte[] buffer = new byte[4096];
                    for (int len = zis.read(buffer); len > 0; len = zis.read(buffer)) {
                        fos.write(buffer, 0, len);
                    }
                }
            }
        }
    }

    private final void flatten(Path output) throws IOException {
        List<Path> children = Files.list(output)
                .collect(toList());

        if (children.size() == 1) {
            Path path = children.get(0);
            Files.list(path)
                    .forEach(f -> {
                        try {
                            System.out.printf("Moving %s to %s.\n", f.toFile().getAbsolutePath(),
                                    output.toFile().getAbsolutePath());
                            Files.move(f, Paths.get(output.toFile().getAbsolutePath(), f.toFile().getName()));
                        } catch (IOException e) {
                            throw new UncheckedIOException(e);
                        }
                    });

            Files.delete(path);
        }
    }
}

---test.txt
代码

test.zip
--- test
------ test.txt
<someFolder>
--- test.txt
public class Main {

    public static void main(String[] args) throws IOException {
        Main main = new Main();

        Path input = main.getInputPath(args);
        Path output = main.getOutputPath(args);

        main.extract(input, output);
        main.flatten(output);
    }

    private final Path getInputPath(String[] args) {
        if (args.length < 1) {
            throw new IllegalArgumentException("Usage: Main <inputFile> [<outputDirectory>]");
        }

        Path input = Paths.get(args[0]);

        if (!isRegularFile(input)) {
            throw new IllegalArgumentException(String.format("%s is not a file.", input.toFile().getAbsolutePath()));
        }

        return input;
    }

    private final Path getOutputPath(String[] args) throws IOException {
        return args.length < 2 ? Files.createTempDirectory(null) :
                Files.createDirectories(Paths.get(args[1]));
    }

    private final void extract(Path input, Path output) throws IOException {
        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(input.toFile()))) {
            for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) {
                String fileName = ze.getName();

                if (fileName.contains("__MACOSX")) {
                    continue;
                }

                File file = new File(output.toFile(), fileName);

                if (ze.isDirectory()) {
                    Files.createDirectories(file.toPath());
                    continue;
                }

                System.out.println("Extracting: " + file.getAbsolutePath());

                try (FileOutputStream fos = new FileOutputStream(file, true)) {
                    byte[] buffer = new byte[4096];
                    for (int len = zis.read(buffer); len > 0; len = zis.read(buffer)) {
                        fos.write(buffer, 0, len);
                    }
                }
            }
        }
    }

    private final void flatten(Path output) throws IOException {
        List<Path> children = Files.list(output)
                .collect(toList());

        if (children.size() == 1) {
            Path path = children.get(0);
            Files.list(path)
                    .forEach(f -> {
                        try {
                            System.out.printf("Moving %s to %s.\n", f.toFile().getAbsolutePath(),
                                    output.toFile().getAbsolutePath());
                            Files.move(f, Paths.get(output.toFile().getAbsolutePath(), f.toFile().getName()));
                        } catch (IOException e) {
                            throw new UncheckedIOException(e);
                        }
                    });

            Files.delete(path);
        }
    }
}
公共类主{
公共静态void main(字符串[]args)引发IOException{
Main Main=新Main();
路径输入=main.getInputPath(args);
路径输出=main.getOutputPath(args);
main.extract(输入、输出);
主。展平(输出);
}
私有最终路径getInputPath(字符串[]args){
如果(参数长度<1){
抛出新的IllegalArgumentException(“用法:Main[]);
}
路径输入=Path.get(args[0]);
如果(!isRegularFile(输入)){
抛出新的IllegalArgumentException(String.format(“%s不是文件”)、input.toFile().getAbsolutePath());
}
返回输入;
}
私有最终路径getOutputPath(字符串[]args)引发IOException{
返回args.length<2?Files.createTempDirectory(null):
Files.createDirectories(path.get(args[1]);
}
私有最终无效提取(路径输入、路径输出)引发IOException{
try(ZipInputStream zis=newzipinputstream(newfileinputstream(input.toFile())){
for(ZipEntry ze=zis.getnextery();ze!=null;ze=zis.getnextery()){
字符串文件名=ze.getName();
if(fileName.contains(“\uuuMacosx”)){
持续
}
File File=新文件(output.toFile(),文件名);
if(ze.isDirectory()){
Files.createDirectories(file.toPath());
持续
}
System.out.println(“提取:“+file.getAbsolutePath());
try(FileOutputStream fos=newfileoutputstream(file,true)){
字节[]缓冲区=新字节[4096];
for(int len=zis.read(缓冲区);len>0;len=zis.read(缓冲区)){
fos.写入(缓冲区,0,len);
}
}
}
}
}
私有最终空心展平(路径输出)引发IOException{
列表子项=文件。列表(输出)
.collect(toList());
if(children.size()==1){
Path=children.get(0);
文件列表(路径)
.forEach(f->{
试一试{
System.out.printf(“将%s移动到%s。\n”,f.toFile().getAbsolutePath(),
output.toFile().getAbsolutePath());
文件.move(f,path.get(output.toFile().getAbsolutePath(),f.toFile().getName());
}捕获(IOE异常){
抛出新的未选中异常(e);
}
});
删除(路径);
}
}
}

显示您的解压缩代码。与Java或grails无关。标签removed@AbhijitSarkar刚刚添加了代码。我希望这不会给我的问题增加任何不必要的复杂性
grails
标签完全误导-再次删除。在这个问题中没有一点特定于grails的代码。@mosawi它不是这样工作的。我们不是那些回答你随意向我们提出的问题而获得报酬的顾问。我们是喜欢解决问题的程序员。为了做到这一点,我们首先需要理解上下文。如果你想处理模糊的信息,请询问你的上司。随机投票,想解释一下吗?谢谢@AbhijitSarkar。不确定是谁否决了你的答案或我的问题,但这个答案很有效。我希望得到一个简单的解决方案,但这看起来比我在第一行中使用的展平方法要好得多
List children=Files.List(output.collect(toList())toList()在哪里?我也没有看到
isRegularFile
方法?有兴趣了解它如何检查文件类型这就是IDE存在的原因。要求它进行静态导入。