我有一个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中。
发布于 2019-06-12 03:25:41
下面的代码遍历给定的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();
});
}
发布于 2016-08-11 21:42:31
Apache Commons Compress 模块可能可以帮助您遍历文件。
下面是一个示例提取,它可以迭代多个文件并提取字节内容示例
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ZipTest {
public static void main(String[] args) throws FileNotFoundException, IOException {
String fileName = "C:\\temp\\ECDS-File-Upload-Processed.zip";
String destinationDir = "C:\\temp\\mango";
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(fileName));
ZipEntry zipEntry = zipInputStream.getNextEntry();
byte[] buffer = new byte[1024];
while (zipEntry != null) {
String zipFileName = zipEntry.getName();
File extractedFile = new File(destinationDir + File.separator + zipFileName);
new File(extractedFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(extractedFile);
int len;
while ((len = zipInputStream.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
zipEntry = zipInputStream.getNextEntry();
}
zipInputStream.closeEntry();
zipInputStream.close();
}
}
https://stackoverflow.com/questions/38894464
复制相似问题