解压缩多部分文件 带子目录和不带子目录,因为我没有向用户提供任何如何压缩文件的说明,因此我需要找到/搜索 Zip 文件中可能包含目录和子目录的所有文件,并将所有文件保存在单独不同的文件夹中。
所以基本上它是某种智能解压缩,它使用 ZipEntry 检测目录,然后跳过并查找要写入文件夹的文件。
我已经编写了一段代码,但我什至还没有接近它,因为我只得到一个文件,其中也没有目录。
String outputPath="C:\\Users\\Plootus\\exceldocs\\";
FileSystem fileSystem = FileSystems.getDefault();
try
{
ZipInputStream zis=new ZipInputStream(serverFile.getInputStream());
BufferedInputStream bis=null;
InputStream is=null;
//Get file entries
ZipEntry entry=null;
//We will unzip files in this folder
while ( (entry = zis.getNextEntry()) != null ) {
System.out.println(entry.getName());
if(!entry.isDirectory()) {
System.out.println(entry.getName());
is = zis;
bis = new BufferedInputStream(is);
String uncompressedFileName = outputPath+toolName+entry.getName();
Path uncompressedFilePath = fileSystem.getPath(uncompressedFileName);
Files.createFile(uncompressedFilePath);
FileOutputStream fileOutput = new FileOutputStream(uncompressedFileName);
while (bis.available() > 0)
{
fileOutput.write(bis.read());
}
fileOutput.close();
System.out.println("Written :" + entry.getName());
bis.close();
is.close();
}
}
zis.close();
return true;
}
catch(IOException e)
{
return false;
}
return false;
目标:Zip 文件包含可能的条目
1.) abc.zip(多部分文件)
-folder1-arkan.csv,dan.csv,kud.csv
abc.zip(多部分文件)
-folder1--bio.csv(file)-folder-2(inside folder1)-arkan.csv,dan.csv,kud.csv
abc.zip(多部分文件)
-arkan.csv,dan.csv,kud.csv
最佳答案
不是从 MultipartFile 中提取并处理条目,因为 ZipEntry(如 @Jokkeri 所说)是不可能的,因此我找到了其他方法来做到这一点。
我将保存该文件,并在操作完成后将其删除。
收到多部分文件后,我使用文件对象(saveZip)保存文件
try(ZipFile file = new ZipFile(saveZip.getCanonicalPath()))
{
FileSystem fileSystem = FileSystems.getDefault();
//Get file entries
Path inputpath=fileSystem.getPath(file.getName());
Enumeration<? extends ZipEntry> entries = file.entries();
//We will unzip files in this folder
File directory=new File(zipFilePath.concat(username+"-"+toolName));
if(!directory.exists()) {
directory.mkdir();
}
//Iterate over entries
while (entries.hasMoreElements())
{
ZipEntry entry = entries.nextElement();
String abc[]=entry.getName().split("/");
//Else create the file
if(!entry.isDirectory())
{
InputStream is = file.getInputStream(entry);
BufferedInputStream bis = new BufferedInputStream(is);
String uncompressedFileName = zipFilePath +username+"-"+toolName+"/"+ abc[abc.length-1];
Path uncompressedFilePath = fileSystem.getPath(uncompressedFileName);
if(Files.notExists(uncompressedFilePath))
Files.createFile(uncompressedFilePath);
FileOutputStream fileOutput = new FileOutputStream(uncompressedFileName);
while (bis.available() > 0)
{
fileOutput.write(bis.read());
}
fileOutput.close();
System.out.println("Written :" + entry.getName());
is.close();
bis.close();
}
}
file.close();
Files.deleteIfExists(inputpath);
return true;
}catch(IOException e)
{
e.printStackTrace();
return false;
}
关于java - 解压缩带子目录和不带子目录的多部分文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51819470/