要解压 Zip 文件并读取文件内容,可以使用 Java 的 ZipInputStream 类和 BufferedReader 类。\n\n下面是一个示例代码,演示如何解压 Zip 文件并读取文件内容:\n\njava\nimport java.io.BufferedReader;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipInputStream;\n\npublic class UnzipAndReadFileContent {\n public static void main(String[] args) {\n String zipFilePath = "path/to/your/zip/file.zip";\n \n try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath))) {\n ZipEntry entry = zipInputStream.getNextEntry();\n \n while (entry != null) {\n if (!entry.isDirectory()) {\n System.out.println("File: " + entry.getName());\n \n // 读取文件内容\n BufferedReader reader = new BufferedReader(new InputStreamReader(zipInputStream));\n String line;\n while ((line = reader.readLine()) != null) {\n System.out.println(line);\n }\n reader.close();\n }\n \n zipInputStream.closeEntry();\n entry = zipInputStream.getNextEntry();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}\n\n\n在上面的代码中,首先创建一个 ZipInputStream 对象来读取 Zip 文件。然后使用 getNextEntry() 方法获取 Zip 文件中的下一个条目(文件或目录)。如果当前条目是文件,我们使用 BufferedReader 类读取文件内容,并将其打印出来。最后,使用 closeEntry() 方法关闭当前条目,然后继续循环读取下一个条目,直到所有条目都被读取完毕。\n\n请注意,上面的代码仅演示了如何读取 Zip 文件中的文件内容。如果需要解压整个 Zip 文件,请使用 ZipOutputStream 类和 ZipEntry 类来创建新的文件并将内容写入其中。


原文地址: https://www.cveoy.top/t/topic/p0wB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录