[英]Unzipping Multipart file with and without subdirectories
解壓縮包含和不包含子目錄的 多部分文件 ,因為我沒有向用戶提供任何有關如何壓縮文件的說明,因此我需要從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(Mutlipart文件)
-folder1--bio.csv(file)-folder-2(inside folder1)-arkan.csv,dan.csv,kud.csv
abc.zip(Mutlipart文件)
-arkan.csv,dan.csv,kud.csv
而不是從MultipartFile中提取並像ZipEntry那樣處理條目(如@Jokkeri所說),因此我發現了另一種方法。
我將保存該文件,操作完成后將其刪除。
收到多部分文件后,我使用File對象(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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.