简体   繁体   English

Java-使用子文件夹从不同位置创建包含多个文件的Zip文件

[英]Java - Create Zip-file with multiple files from different locations with subfolders

I am trying to generate a zip file in Java, that contains several files of different types (eg images, fonts etc) that are lying in different locations. 我正在尝试用Java生成一个zip文件,其中包含位于不同位置的几个不同类型的文件(例如图像,字体等)。 Furthermore I want the zip file to have subfolders where the files are put by their type (eg images should go to the images folder within the zip. 此外,我希望压缩文件具有子文件夹,这些子文件夹用于按文件的类型放置文件(例如,图像应转到zip中的images文件夹)。

These are the files that I have (each can be in a different location): 这些是我拥有的文件(每个文件可以位于其他位置):

  • index.html index.html
  • img1.jpg img1.jpg
  • img2.jpg img2.jpg
  • font1.woff font1.woff
  • font2.woff font2.woff
  • style.css style.css
  • custom.js custom.js

And this is how they should be in the zip file: 这就是它们应该在zip文件中的方式:

  • index.html index.html
  • images/img1.jpg 图片/img1.jpg
  • images/img2.jpg 图片/img2.jpg
  • fonts/font1.woff 字体/font1.woff
  • fonts/font2.woff fonts / font2.woff
  • js/custom.js js / custom.js
  • css/styles.css css / styles.css

So far I have managed to take one file in a specific path and prompt the user for the output location. 到目前为止,我已经设法在特定路径中获取一个文件,并提示用户输入输出位置。 A zip-file will be generated with the file that is specified in the input. 将使用输入中指定的文件生成一个zip文件。 Here is the code I have so far: 这是我到目前为止的代码:

JFrame parentFrame = new JFrame();

JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Speicherort auswählen");   

int userSelection = fileChooser.showSaveDialog(parentFrame);
String pathToFile;

if (userSelection == JFileChooser.APPROVE_OPTION) {
    File fileToSave = fileChooser.getSelectedFile();
    print(fileToSave.getAbsolutePath());
    pathToFile = fileToSave.getAbsolutePath();
}

pathToFile = pathToFile.replace("\\", "/");

String outFileName = pathToFile;
String inFileName = "C:/Users/asoares/Desktop/mobio_export_test/index.html";
ZipOutputStream zos = null; 
FileInputStream fis = null;

try {
    zos = new ZipOutputStream(new FileOutputStream(outFileName));
    fis = new FileInputStream(inFileName);
    zos.putNextEntry(new ZipEntry(new File(inFileName).getName()));
    int len;
    byte[] buffer = new byte[2048];
    while((len = fis.read(buffer, 0, buffer.length)) > 0) {
        zos.write(buffer, 0, len);
    }
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} finally { 
    if(fis != null){ 
        try { 
            fis.close(); 
        } catch (IOException e) {} 
    } 
    if(zos != null){ 
        try { 
            zos.closeEntry(); 
            zos.close(); 
        } catch (IOException e) {} 
    } 
}

I would be really glad if someone can help me!!! 如果有人可以帮助我,我将非常高兴!!!

It should work like this. 它应该像这样工作。

The zip directory name should at best be created by another method (there are more image types than jpg :)). zip目录名称最多应使用另一种方法创建(图像类型多于jpg :)。

public static Path zip(List<Path> files, Path zipFileTarget) throws IOException {
    try (FileOutputStream fos = new FileOutputStream(zipFileTarget.toFile());
         ZipOutputStream zos = new ZipOutputStream(fos)) {
        if (!Files.exists(zipFileTarget))
            Files.createFile(zipFileTarget);
        createEntries(files, zos);
        zos.close();
        return zipFileTarget;
    }
}

private static List<String> createEntries(List<Path> files, ZipOutputStream zos) throws IOException {
    List<String> zippedFiles = new ArrayList<>();
    Matcher matcherFileExt = Pattern.compile("^.*\\.([^.]+)$").matcher("");
    for (Path f : files) {
        if (Files.isRegularFile(f)) {
            String fileName = f.getFileName().toString();
            String fileExt = matcherFileExt.reset(fileName).matches()
                    ? matcherFileExt.replaceAll("$1")
                    : "unknown";
            // You should determine the dir name with a more sophisticated
            // approach.
            String dir;
            if      (fileExt.equals("jpg")) dir = "images";
            else if (fileExt.equals("woff")) dir = "fonts";
            else    dir = fileExt;

            zos.putNextEntry(new ZipEntry(dir + "/" + fileName));
            Files.copy(f, zos);
            zippedFiles.add(fileName);
        }
    }
    return zippedFiles;
}

Edit: this approach works with java 1.7+. 编辑:此方法适用于Java 1.7+。 You can easily convert a File object to a Path object by calling its toPath() method. 您可以通过调用其toPath()方法轻松地将File对象转换为Path对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Java 从 S3 并行下载多个文件到一个 zip 文件 - Download multiple files in parallel to a zip-file from S3 using Java Java:递归地将文件添加到zip文件但没有完整路径 - Java: Add files to zip-file recursively but without full path 如何使用 Liferay 将多个文件下载为 zip 文件? - How to download multiple files as a zip-file using Liferay? 在Java中创建Zip文件而不使用byte [] - Create Zip-File in java without using byte[] 播放压缩文件中的音频文件 - Playing audio files packed in zip-File 如何从客户端计算机下载zip文件,而不是使用Java在浏览器中打开文件? - how to download zip-file from client machine instead of opening file in browser using java? 如何从Http-Request的Raw-Data创建Zip-File? - How to create Zip-File from Raw-Data from Http-Request? 在Java中运行时从zip文件读取ESRI shapefile - DataStoreFinder.getDataStore(connectParameters)返回null - Reading an ESRI shapefile from a zip-file during Runtime in Java - DataStoreFinder.getDataStore(connectParameters) returns null 解压缩后打开/下载zip文件时出现问题(Java / ZipInputStream) - Problem opening/downloading zip-file after decompression (Java/ZipInputStream) 如何使用来自不同位置的文件创建Java程序 - How to create a Java program with files from different locations
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM