Scenario: I have code that calls a soap web service, gets an attachment which is a zip file. 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:
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. Since it's a CSV file, I need to parse LINE BY LINE. 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).
Can you tell me if the inner for loop reads the content of the file LINE by 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. And the glue what you need is InputStreamReader
. Then you can wrap the ZipInputStream
as
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:
String line;
while((line=br.readLine())!=null){
<process one line>
}