我在特定位置有多个zip文件。 每个Zip文件中都包含1个CSV文件。我尝试下面的代码读取每个zip文件并获取zip内的CSV计数,最后,我正在打印每个文件的行总和。代码正在执行,没有错误,但是打印的最终值无效。任何帮助将不胜感激。
File1.csv-位于File1.Zip中
File2.csv-位于File2.Zip中
public static void main(String[] args)
{
String archivePath = "C:\\Users\\Documents\\";
String FileName ="";
LineNumberReader reader = null;
long totalLines = 0;
try (DirectoryStream<Path> dir = Files.newDirectoryStream(Paths.get(archivePath), "*.zip"))
{
for (Path entry : dir)
{
Path sourceCsvFileName = entry.getFileName();
FileName = sourceCsvFileName.toString();
// System.out.println(" File name: "+ FileName); // prints FileName Eg: File1.zip , File2.zip
// Below logic to Read number of lines for each iterated CSV which is inside zip file (NOTE: Stop reading on encountering empty row)
reader = new LineNumberReader(new FileReader(new File(archivePath + FileName)));
while ((reader.readLine()) != null);
totalLines = totalLines + reader.getLineNumber();
reader.close();
}
System.out.println("Total sum of rows from all files-> " + totalLines); // expected o/p (5+2): 7 actual o/p : 13
}
catch(Exception e)
{
e.printStackTrace();
}
}
答案 0 :(得分:1)
您将需要使用ZipFile / ZipEntry类读取zip中的文件。 以下代码应满足您的要求:
try (DirectoryStream<Path> dir = Files.newDirectoryStream(Paths.get(archivePath), "*.zip")) {
for (Path entry : dir) {
ZipFile zipFile = new ZipFile(entry.getFileName().toString());
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while(entries.hasMoreElements()){
ZipEntry zipEntry = entries.nextElement();
reader = new BufferedReader(new InputStreamReader(zipFile.getInputStream(zipEntry),"UTF-8"));
while ((reader.readLine()) != null) {
totalLines++;
}
}
reader.close();
}
System.out.println("Total sum of rows from all files-> " + totalLines); // expected o/p (5+2): 7 actual o/p : 13
} catch (Exception e) { e.printStackTrace(); }