簡體   English   中英

是否可以使用java FileSystem創建一個新的zip文件?

[英]Is it possible to create a NEW zip file using the java FileSystem?

我已經使用java 7提供的FileSystem成功修改了(現有)zip文件的內容,但是當我嘗試通過此方法創建一個新的zip文件時,它失敗了,並顯示錯誤消息: "zip END header not found" ,這是合乎邏輯的,因為我正在這樣做,首先我創建一個文件( Files.createFile )這是一個完全空的文件,然后我嘗試訪問它的文件系統,因為該文件是空的它無法在zip中找到任何標題, 我的問題是有沒有辦法用這種方法創建一個完全空的新zip文件? 我考慮過的黑客是在zip文件中添加一個空的新ZipEntry然后使用那個新的空文件來創建基於它的文件系統,但是我真的想讓oracle的人實現更好(更容易) )用nio和文件系統做到這一點的方法......

這是我的代碼(創建文件系統時出現錯誤):

if (!zipLocation.toFile().exists()) {
        if (creatingFile) {
            Files.createFile(zipLocation);
        }else {
            return false;
        }
    } else if (zipLocation.toFile().exists() && !replacing) {
        return false;
    } 
    final FileSystem fs = FileSystems.newFileSystem(zipLocation, null);
.
.
.

zipLocation是路徑creatingFile是一個布爾

答案:在我的特殊情況下,由於路徑中的空格,給出的答案沒有正常工作,因此我必須按照我不想要的方式進行:

Files.createFile(zipLocation);
ZipOutputStream out = new ZipOutputStream(
    new FileOutputStream(zipLocation.toFile()));
out.putNextEntry(new ZipEntry(""));
out.closeEntry();
out.close();

這並不意味着給定的答案是錯誤的,它只是對我的具體情況不起作用

Oracle網站中所述

public static void createZip(Path zipLocation, Path toBeAdded, String internalPath) throws Throwable {
    Map<String, String> env = new HashMap<String, String>();
    // check if file exists
    env.put("create", String.valueOf(Files.notExists(zipLocation)));
    // use a Zip filesystem URI
    URI fileUri = zipLocation.toUri(); // here
    URI zipUri = new URI("jar:" + fileUri.getScheme(), fileUri.getPath(), null);
    System.out.println(zipUri);
    // URI uri = URI.create("jar:file:"+zipLocation); // here creates the
    // zip
    // try with resource
    try (FileSystem zipfs = FileSystems.newFileSystem(zipUri, env)) {
        // Create internal path in the zipfs
        Path internalTargetPath = zipfs.getPath(internalPath);
        // Create parent directory
        Files.createDirectories(internalTargetPath.getParent());
        // copy a file into the zip file
        Files.copy(toBeAdded, internalTargetPath, StandardCopyOption.REPLACE_EXISTING);
    }
}

public static void main(String[] args) throws Throwable {
    Path zipLocation = FileSystems.getDefault().getPath("a.zip").toAbsolutePath();
    Path toBeAdded = FileSystems.getDefault().getPath("a.txt").toAbsolutePath();
    createZip(zipLocation, toBeAdded, "aa/aa.txt");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM