I am trying to use Scanner read ZipInputStream line by line, below is the code i have
ZipInputStream inputStream = new ZipInputStream(bodyPartEntity.getInputStream());
inputStream.getNextEntry();
Scanner sc = new Scanner(inputStream);
while (sc.hasNextLine()) {
log.info(sc.nextLine());
}
and it works fine.
But I have a question, what if a user compressed an image or different type of files (not CSV) as a Zip. Is there a way that I can check that so I can throw an exception for it? Also, is there a way to read next file
?
For now, if I compressed multiple files, I'm only able to read one. And then sc.hasNextLine()
will be equal to false.
Anyway, I can read the next file?
you should loop over your zip file like this:
ZipEntry entry;
while((entry = inputStream.getNextEntry())!=null){
// do your logic here...
// for example: entry.getName()
}
For the file type, you could use something like this, inside of while loop:
MimetypesFileTypeMap mtft = new MimetypesFileTypeMap();
String mimeType = mtft.getContentType(entry.getName());
System.out.println(entry.getName()+" type: "+ mimeType);
Happy coding!