【问题标题】:Java - Create Zip-file with multiple files from different locations with subfoldersJava - 使用来自不同位置的多个文件和子文件夹创建 Zip 文件
【发布时间】:2018-04-29 23:32:51
【问题描述】:

我正在尝试在 Java 中生成一个 zip 文件,其中包含位于不同位置的多个不同类型的文件(例如图像、字体等)。此外,我希望 zip 文件具有按类型放置文件的子文件夹(例如,图像应该转到 zip 中的图像文件夹。

这些是我拥有的文件(每个文件可以在不同的位置):

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

这就是它们在 zip 文件中的样子:

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

到目前为止,我已经设法在特定路径中获取一个文件并提示用户输入输出位置。将使用输入中指定的文件生成一个 zip 文件。这是我到目前为止的代码:

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

如果有人可以帮助我,我会很高兴!!!

【问题讨论】:

    标签: java zip subdirectory


    【解决方案1】:

    它应该像这样工作。

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

    编辑:这种方法适用于 java 1.7+。您可以通过调用toPath() 方法轻松地将File 对象转换为Path 对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-23
      • 1970-01-01
      • 2015-12-25
      • 2013-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多