从嵌入式ZIP存档中读取文件的Java代码

bluesky1年前 ⋅ 143 阅读

ChatGPT的回答仅作参考:

以下是从嵌入式ZIP存档中读取文件的Java代码示例:

```java
import java.io.*;
import java.util.zip.*;

public class ReadEmbeddedZipFile {
    public static void main(String[] args) throws IOException {
        // Open the embedded ZIP archive
        InputStream inputStream = ReadEmbeddedZipFile.class.getResourceAsStream("/embedded.zip");
        ZipInputStream zipInputStream = new ZipInputStream(inputStream);

        // Iterate through the entries in the ZIP archive
        ZipEntry zipEntry;
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            // If the entry is a file, read its contents
            if (!zipEntry.isDirectory()) {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length;
                while ((length = zipInputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }
                String fileContents = outputStream.toString("UTF-8");
                System.out.println("File " + zipEntry.getName() + " contents: " + fileContents);
            }
            zipInputStream.closeEntry();
        }

        // Close the ZIP archive
        zipInputStream.close();
    }
}
```

这个示例代码打开了一个名为“embedded.zip”的嵌入式ZIP存档,并遍历了存档中的所有条目。对于每个文件条目,它读取了文件的内容并将其打印到控制台上。请注意,这个示例假设所有文件都使用UTF-8编码。如果您的文件使用不同的编码,请相应地更改代码。

全部评论: 0

    相关推荐