Sometimes we need to find whehter the zip file contains valid files or not. Suppose you have a zip file which contains multiple file you want to upload that zip file only if it contains files having extension jpeg,jpg,png,gif,tiff only, so we can do this by using below example.
Example: In the below example I want to check whether my zip file contains files having extension jpeg,jpg,png,gif,tiff only.
1. The below function will check whether file has valid extension or not:
String extentions = jpeg,jpg,png,gif,tiff;
public static boolean isValidFileExtenstion(String fileName, String fileExtensions){
if(fileExtensions.isEmpty())return true;
StringTokenizer st=new StringTokenizer(fileExtensions, ",");
String fileExt = fileName.substring(fileName.lastIndexOf(".")+1);
while(st.hasMoreElements()){
String invalidExt=(String)st.nextToken().trim();
if(fileExt.equalsIgnoreCase(invalidExt))
return false;
}
return true;
}
2. The below function will extract the zip file and check that it contains valid files
public static boolean isContainsInvalidFilesInZip(String zipFilePath, String extentions) throws IOException{
if(extentions.isEmpty())return false;
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipFilePath));
final ZipInputStream zipInputStream = new ZipInputStream(bis);
boolean isValid=false;
try {
ZipEntry zipentry;
while ((zipentry = zipInputStream.getNextEntry()) != null) {
if (zipentry.isDirectory()) {
zipentry = zipInputStream.getNextEntry();
continue;
}
isValid = isValidFileExtenstion(zipentry.getName(), extentions);
if(!isValid)return true;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
zipInputStream.close();
}
return false;
}
Hope this will help you :)
0 Comment(s)