read zip file | read html file from zip | read zipfile in java
In java we can read .zip file without extracting zip file manually.
this tutorial help you to read html file without extracting zip file in java .
also you read text/.txt/png file without extracting zip file in java.
Note : set your full zip file path (with .zip extention)
Require Lib : FileUtils
this tutorial help you to read html file without extracting zip file in java .
also you read text/.txt/png file without extracting zip file in java.
Note : set your full zip file path (with .zip extention)
Require Lib : FileUtils
Example :-
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.imageio.ImageIO;
import org.apache.commons.io.FilenameUtils;
/**
*
* @author vishal.khokhar
*/
public class ReaderTest {
public static void main(String[] args) throws Exception {
String path="C:/Documents and Settings/vishal/Desktop/2017-11-23.zip";
ZipFile zip = new ZipFile(path);
for (Enumeration e = zip.entries(); e.hasMoreElements();) {
ZipEntry entry = (ZipEntry) e.nextElement();
if (!entry.isDirectory()) {
if (FilenameUtils.getExtension(entry.getName()).equals("png")) {
byte[] image = getImage(zip.getInputStream(entry));
} else if (FilenameUtils.getExtension(entry.getName()).equals("html")) {
StringBuilder document = getHtmlFile(zip.getInputStream(entry));
System.out.println(document.toString());
} else if (FilenameUtils.getExtension(entry.getName()).equals("txt")) {
StringBuilder textContent = readTextFiles(zip.getInputStream(entry));
System.out.println(textContent.toString());
}
}
}
}
public static StringBuilder getHtmlFile(InputStream in) {
StringBuilder htmlData = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line;
try {
while ((line = bufferedReader.readLine()) != null) {
htmlData.append(line).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return htmlData;
}
public static byte[] getImage(InputStream in) {
try {
BufferedImage bufferedImage = ImageIO.read(in);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static StringBuilder readTextFiles(InputStream in) {
StringBuilder textData = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line;
try {
while ((line = bufferedReader.readLine()) != null) {
textData.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return textData;
}
}
No comments:
Post a Comment