Java endsWith() Method Example
Hello Readers…
In this article
we will learn the use of endsWith() method in java, for that we will see the below
example in which we have to find out zip file in the given path and if zip file
is present then unzip it and display the name of files and total number of
files which is present in zip files. In this example I have created a folder
Tutorial in my E:\\Tutorial drive in which there are 2 zip file present zipFile1.zip
and zipFile2.zip and each zip contains four text file i.e., file1.txt , file2.txt,
file3.txt and file4.txt . See below example…
package com.ma3.common;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class TheTechMatin {
public static void findZipIn(String zipFilePath) {
File zipFile = new File(zipFilePath);
String[] files = zipFile.list();
String zipFileName=null;
int zipCount=0;
List<String>
listOfZipFiles =new ArrayList<>();
if(files != null) {
for (String file : files) {
if(file != null) {
if (file.endsWith(".zip")) {
zipCount++;
zipFileName=file;
listOfZipFiles.add(zipFileName);
System.out.println("Zip File Name : "+zipFileName);
System.out.println("=========================");
//custom method
unzipFile(zipFilePath+"/"+file, zipFileName);
}
}
}
System.out.println("Total"+zipCount+" Zip
Files Found "+ listOfZipFiles);
}
else {
System.out.println("File Not Found : "+ zipFilePath);
}
}
public static void unzipFile(String zipFile, String zipFileName) {
//extract zip file and display name of files present in zip
FileInputStream fis = null;
ZipInputStream zipIs = null;
ZipEntry zEntry = null;
int count=0;
try {
fis = new FileInputStream(zipFile);
zipIs = new ZipInputStream(new BufferedInputStream(fis));
while((zEntry = zipIs.getNextEntry()) != null){
count++;
System.out.println(count+".
"+zEntry.getName());
}
System.out.println("Total : "+count+" Files
Found In "+zipFileName);
System.out.println("=========================");
zipIs.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String pathStr = "E:\\Tutorial";
findZipIn(pathStr);
}
output
Zip File Name : zipFile1.zip
=========================
1. ZipFile/file1.txt
2. ZipFile/file2.txt
3. ZipFile/file3.txt
4. ZipFile/file4.txt
Total : 4 Files Found In zipFile1.zip
=========================
Zip File Name : ZipFile2.zip
=========================
1. ZipFile/file1.txt
2. ZipFile/file2.txt
3. ZipFile/file3.txt
4. ZipFile/file4.txt
Total : 4 Files Found In ZipFile2.zip
===================================
Total 2 Zip Files Found [zipFile1.zip, ZipFile2.zip]
No comments