【发布时间】:2022-01-30 14:53:37
【问题描述】:
当我通过控制台提供 zip 文件夹路径时,我有程序。它将遍历该文件夹中的每个项目(每个子项目、孩子的孩子等)。但是如果它遇到一个 zip 文件夹,它将忽略 zip 文件夹中的所有内容,我需要读取所有内容,包括 zip 文件夹中的文件。
这是遍历每个项目的方法:
public static String[] getLogBuffers(String path) throws IOException//path is given via console
{
String zipFileName = path;
String destDirectory = path;
BufferedInputStream errorLogBuffer = null;
BufferedInputStream windowLogBuffer = null;
String strErrorLogFileContents="";
String strWindowLogFileContents="";
String[] errorString=new String[2];
byte[] buffer = new byte[1024];
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFileName));
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null)
{
String filePath = destDirectory + "/" + zipEntry.getName();
System.out.println("unzipping" + filePath);
if (!zipEntry.isDirectory())
{
if (zipEntry.getName().endsWith("errorlog.txt"))
{
ZipFile zipFile = new ZipFile(path);
InputStream errorStream = zipFile.getInputStream(zipEntry);
BufferedInputStream bufferedInputStream=new BufferedInputStream(errorStream);
byte[] contents = new byte[1024];
System.out.println("ERRORLOG NAME"+zipEntry.getName());
int bytesRead = 0;
while((bytesRead = bufferedInputStream.read(contents)) != -1) {
strErrorLogFileContents += new String(contents, 0, bytesRead);
}
}
if (zipEntry.getName().endsWith("windowlog.txt"))
{ ZipFile zipFile = new ZipFile(path);
InputStream windowStream = zipFile.getInputStream(zipEntry);
BufferedInputStream bufferedInputStream=new BufferedInputStream(windowStream);
byte[] contents = new byte[1024];
System.out.println("WINDOWLOG NAME"+zipEntry.getName());
int bytesRead = 0;
while((bytesRead = bufferedInputStream.read(contents)) != -1) {
strWindowLogFileContents += new String(contents, 0, bytesRead);
}
}
}
zis.closeEntry();
zipEntry = zis.getNextEntry();
}
errorString[0]=strErrorLogFileContents;
errorString[1]=strWindowLogFileContents;
zis.closeEntry();
zis.close();
System.out.println("Buffers ready");
return errorString;
}
在父 zip 文件夹中访问的项目(我的控制台输出):
unzippingC:logFolders/logX3.zip/logX3/
unzippingC:logFolders/logX3.zip/logX3/Anan/
unzippingC:logFolders/logX3.zip/logX3/Anan/errorreports/
unzippingC:logFolders/logX3.zip/logX3/Anan/errorreports/2021-11-23_103518.zip
unzippingC:logFolders/logX3.zip/logX3/Anan/errorreports/errorlog.txt
unzippingC:logX3.zip/logX3/Anan/errorreports/version.txt
unzippingC:logFolders/logX3.zip/logX3/Anan/errorreports/windowlog.txt
如您所见,该程序只运行到 2021-11-23_103518.zip,之后进入另一条路径,但 2021-11-23_103518.zip 有我需要访问的子项(文件) 感谢任何帮助,谢谢
【问题讨论】:
-
尽管 Windows 使 zip 文件的行为有点像文件夹(包括我自己在内的许多人认为这是一个糟糕的主意),但 zip 文件在任何方面都不是文件夹。要读取另一个 zip 文件中的 zip 文件,您需要一个新的 ZipInputStream 或一个新的 ZipFile。 (从另一个 ZipInputStream 创建一个 ZipInputStream 并从中读取可能会很慢,因此我建议将条目复制到一个临时文件中,从中读取,然后将其删除。)
标签: java zip java-io zipinputstream