请帮忙。我想从 zip 文件中读取文件。我的 zip 文件是 MultipartFile。然后我使用 ZipInputStream 获取其输入文件,但是,它给出了未找到文件的错误。
public String importProject(MultipartFile file) throws IOException, ParseException {
//Reading the input of zip file,
ZipInputStream zin = new ZipInputStream(file.getInputStream());
ZipEntry ze;
FileInputStream excel = null;
ArrayList<AnimationSvg> animationSvgs = new ArrayList<>();
while ((ze = zin.getNextEntry()) != null) {
if(ze.getName().contains(".xlsx")){
excel = new FileInputStream(ze.getName());
}
else if(ze.getName().contains(".svg")){
FileInputStream svg = new FileInputStream(ze.getName());
AnimationSvg animationSvg = new AnimationSvg();
animationSvg.setName(ze.getName());
StringBuilder svgContent = new StringBuilder();
int i;
while((i = svg.read())!=-1) {
svgContent.append(String.valueOf((char) i));
}
animationSvg.setSvgContent(String.valueOf(svgContent));
animationSvgs.add(animationSvg);
}
zin.closeEntry();
}
zin.close();
最佳答案
zip 存档中的条目不是文件。它只是 zip 中的一系列压缩字节。
根本不要使用 FileInputStream。只需从 ZipInputStream 中读取 zip 条目数据即可:
Path spreadsheetsDir = Files.createTempDirectory(null);
Path excel = null;
while ((ze = zin.getNextEntry()) != null) {
String name = ze.getName();
if (name.endsWith(".xlsx")) {
excel = spreadsheetsDir.resolve(name));
Files.copy(zin, excel);
} else if (name.endsWith(".svg")) {
AnimationSvg animationSvg = new AnimationSvg();
animationSvg.setName(name);
animationSvg.setSvgContent(
new String(zin.readAllBytes(), StandardCharsets.UTF_8));
animationSvgs.add(animationSvg);
}
zin.closeEntry();
}
关于java - 如何读取zip文件中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52880088/