简体   繁体   English

关于从Java中的ZipInputStream / ZipEntry读取的问题

[英]Question about reading from a ZipInputStream/ZipEntry in java

Scenario: I have code that calls a soap web service, gets an attachment which is a zip file. 场景:我有调用Soap Web服务的代码,获得的附件是zip文件。 Then unzips it, goes through all the files, gets the one file I want, which is a csv file, and gets the content of the csv file: 然后将其解压缩,浏览所有文件,获取我想要的一个文件,即csv文件,并获取csv文件的内容:

public static void unzipTry2(AttachmentPart att) throws IOException, SOAPException {
    try (ZipInputStream zis = new ZipInputStream(att.getRawContent())) {
        byte[] buffer = new byte[1024];
        for (ZipEntry zipEntry = zis.getNextEntry(); zipEntry != null; zipEntry = zis.getNextEntry()) {
            if (zipEntry.isDirectory()) {
                continue;
            }
            if (!zipEntry.getName().equals("FileIwant.csv")) {
                continue; //if it's not the file I want, skip this file
            }
            System.out.println(zipEntry.getName());
            for (int len = zis.read(buffer); len > 0; len = zis.read(buffer)) {
                //System.out.write(buffer, 0, len);
                String testString = new String(buffer,0,len);
                processCSVString(testString);
            }

        }
    }
}

It works just fine. 它工作正常。 However the CSV file that I am getting only contains one line, which is expected now, but in the future it may contain multiple lines. 但是,我得到的CSV文件仅包含一行,现在应该可以,但是将来可能包含多行。 Since it's a CSV file, I need to parse LINE BY LINE. 由于它是CSV文件,因此我需要逐行解析。 This code also has to work for the case where the CSV file contains multiple lines, and that is where I am not sure if it works since there is no way to test that (I don't control the input of this method, that all comes from the web service). 此代码还必须适用于CSV文件包含多行的情况,这就是我不确定它是否有效的地方,因为没有办法测试(我不控制此方法的输入,来自网络服务)。

Can you tell me if the inner for loop reads the content of the file LINE by LINE? 您能告诉我内部for循环是否逐行读取LINE文件吗? :

            for (int len = zis.read(buffer); len > 0; len = zis.read(buffer)) {
                //System.out.write(buffer, 0, len);
                String testString = new String(buffer,0,len);
                processCSVString(testString);
            }

BufferedReader is the Java "thing" which can read a Reader line-by-line. BufferedReader是Java的“事物”,可以逐行读取Reader And the glue what you need is InputStreamReader . 而您需要的InputStreamReaderInputStreamReader Then you can wrap the ZipInputStream as 然后,您可以将ZipInputStream包装为

BufferedReader br=new BufferedReader(new InputStreamReader(zis))

(preferably in a try-with-resources block), and the classic loop for reading from a BufferedReader looks like this: (最好在try-with-resources块中),并且从BufferedReader读取的经典循环如下所示:

String line;
while((line=br.readLine())!=null){
    <process one line>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM