我有一个 JSP 应用程序,它允许用户上传 ZIP 文件,然后该应用程序将读取 ZIP 中的所有文件并将它们存储在 MySQL 中。
根据建议,我决定使用“Zip File System Provider”来处理 ZIP 文件:
Path zipPath = Paths.get(zipFile.getSubmittedFileName());//returns the path to the ZIP file
FileSystem fs = FileSystems.newFileSystem(zipPath, null);//creates the file system
我尝试使用以下方法遍历它:
for (FileStore store: fs.getFileStores()) {
System.err.println("Store: " + store.name());
}
但是它只循环一次并返回 tmp.zip
,这是整个 ZIP。如何一个一个地提取物理图像文件,以便将它们存储在 MySQL 中。
最佳答案
这是遍历给定 ZIP 文件并打印其中每个文件的前 16 个字节的代码。
Path filePath = Paths.get("somefile.zip");
FileSystem fileSystem = FileSystems.newFileSystem(filePath, null);
byte[] buffer = new byte[16];
Base64.Encoder encoder = Base64.getEncoder();
for (Path rootDirectory : fileSystem.getRootDirectories()) {
Files.walk(rootDirectory).forEach(path -> {
System.out.print(path);
if (Files.isRegularFile(path)) {
System.out.print(" ");
try (InputStream stream = Files.newInputStream(path)) {
int length = stream.read(buffer);
for (int i = 0; i < length; i++) {
byte b = buffer[i];
if (32 <= b && b < 127) {
System.out.print((char) b);
} else {
System.out.printf("\\%02x", b);
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
System.out.println();
});
}
关于java - 如何使用 "Zip File System Provider"在 Java 中遍历 ZIP 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38894464/