Is there a way to unzip a ZIP file with various subfolders in Java without needing to install any additional plugin.
For example, I would like to unzip the file https://services.gradle.org/distributions/gradle-6.4.1-bin.zip with this code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class unzipfile {
private static void unzip(String zipFilePath, String zipFileName, String destDir) {
System.out.print("Extracting " + zipFileName + "...");
File dir = new File(destDir);
// create output directory if it doesn't exist
if(!dir.exists()) dir.mkdirs();
FileInputStream fis;
//buffer for read and write data to file
byte[] buffer = new byte[1024];
try {
fis = new FileInputStream(zipFilePath);
try (ZipInputStream zis = new ZipInputStream(fis)) {
ZipEntry ze = zis.getNextEntry();
while(ze != null){
String fileName = ze.getName();
File newFile = new File(destDir + File.separator + fileName);
//create directories for sub directories in zip
new File(newFile.getParent()).mkdirs();
try (FileOutputStream fos = new FileOutputStream(newFile)) {
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
//close this ZipEntry
ze = zis.getNextEntry();
}
}
fis.close();
System.out.println(" Done!");
} catch (IOException e) {
System.out.println(" Error while extracting " + zipFileName);
Logger.getLogger(unzipfile.class.getName()).log(Level.SEVERE, null, e);
}
}
public static void main(String[] args) {
try{
unzip(args[0], args[1], args[2]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("No valid arguments specified. Usage:\n");
System.out.println("\'java unzipfile [ZIP file path with file name] [file name only] [target directory]\'");
System.exit(1);
}
}
}
I run:
java unzipfile path\to\file\gradle-6.4.1-bin.zip gradle-6.4.1-bin.zip .
But when I run the full application it gives me the message:
Extracting gradle-6.4.1-bin.zip... Error while extracting gradle-6.4.1-bin.zip
may. 27, 2020 5:44:37 P.áM. unzipfile unzip
SEVERE: null
java.io.FileNotFoundException: .\gradle-6.4.1\README (El sistema no puede encontrar la ruta especificada)
at java.base/java.io.FileOutputStream.open0(Native Method)
at java.base/java.io.FileOutputStream.open(FileOutputStream.java:291)
at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:234)
at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:184)
at unzipfile.unzip(unzipfile.java:29)
at unzipfile.main(unzipfile.java:50)
Thanks for your time.
Finally, I've found this working code:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class unzipfile {
public static void main(String[] args) {
String filename = args[0];
File srcFile = new File(filename);
// create a directory with the same name to which the contents will be extracted
String zipPath = filename.substring(0, filename.length()-4);
File temp = new File(zipPath);
temp.mkdir();
ZipFile zipFile = null;
try {
zipFile = new ZipFile(srcFile);
// get an enumeration of the ZIP file entries
Enumeration e = zipFile.entries();
while (e.hasMoreElements()) {
ZipEntry entry = (ZipEntry) e.nextElement();
File destinationPath = new File(zipPath, entry.getName());
//create parent directories
destinationPath.getParentFile().mkdirs();
// if the entry is a file extract it
if (!entry.isDirectory())
System.out.println("Extracting file: " + destinationPath);
try (BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry))) {
int b;
byte buffer[] = new byte[1024];
FileOutputStream fos = new FileOutputStream(destinationPath);
try (BufferedOutputStream bos = new BufferedOutputStream(fos, 1024)) {
while ((b = bis.read(buffer, 0, 1024)) != -1) {
bos.write(buffer, 0, b);
}
}
}
}
}
catch (IOException ioe) {
System.out.println("Error opening zip file" + ioe);
}
finally {
try {
if (zipFile!=null) {
zipFile.close();
}
}
catch (IOException ioe) {
System.out.println("Error while closing zip file" + ioe);
}
}
}
}
Related
I have a basic java program that downloads the file from a link.
I need to make it execute the file in mentioned directory.
I need it to ensure that the file has downloaded.
4.It would be nice if someone could help me.
5.Thanks for anyone willing to help me out.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class URLReader {
public static void copyURLToFile(URL url, File file) {
try {
InputStream input = url.openStream();
if (file.exists()) {
if (file.isDirectory())
throw new IOException("File '" + file + "' is a directory");
if (!file.canWrite())
throw new IOException("File '" + file + "' cannot be written");
} else {
File parent = file.getParentFile();
if ((parent != null) && (!parent.exists()) && (!parent.mkdirs())) {
throw new IOException("File '" + file + "' could not be created");
}
}
FileOutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
input.close();
output.close();
System.out.println("File '" + file + "' downloaded successfully!");
}
catch(IOException ioEx) {
ioEx.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
String sUrl = "http://localhost:8000/TestFile/file.exe";
URL url = new URL(sUrl);
File file = new File("C:/Temp/file.exe");
URLReader.copyURLToFile(url, file);
}
}
I have a scenario where I have to convert binary data to zipfile and I have to download it in java.
I am struck with a part how to convert binary to zipformate. Any help will be appreciated.
You could follow the sample code below to convert your binary data file to zipfile:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
class ZipTest {
public static void zip(String zipFileName, String inputFile)
throws Exception {
File f = new File(inputFile);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
zipFileName));
zip(out, f, f.getName());
System.out.println("zip done");
out.close();
}
private static void zip(ZipOutputStream out, File f, String base)
throws Exception {
out.putNextEntry(new ZipEntry(base));
FileInputStream in = new FileInputStream(f);
int b;
while ((b = in.read()) != -1)
out.write(b);
in.close();
}
public static void main(String[] args) {
try {
ZipTest t = new ZipTest();
t.zip("c:\\test.zip", "c:\\1.txt");
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
Use this example to convert InputStream to ZipInputStream:
FileInputStream fin = new FileInputStream(args[i]);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
System.out.println("Unzipping " + ze.getName());
FileOutputStream fout = new FileOutputStream(ze.getName());
for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}
zin.closeEntry();
fout.close();
}
zin.close();
I have a download button in my webpage where when i click it, it downloads a zip file. now i want to have a function like, when i click the download button the zip file should automatically extract and save in a user defined folder.
i have an idea that if we can create a exe file and add it to the download button then it should automatically extract the zip file and save in folder
%>
<td align="center">
<img onclick="pullReport('<%=reportPath.toString()%>');" title="Click to download this Report" src="./images/down-bt.gif"/>
</td>
</tr>
<%} %>
this is the method that creates zip file
public ActionForward pullReport(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)throws SQLException{
Connection connection=null;
boolean cont=false;
failureList.clear();
logger.info("dispatch = pullReport");
String filePaths=null;
String filePath = null;
String fileName = null;
String srcFileName = null;
String directory = null;
try{
Properties props = Application.getProperties();
String basePath = props.getProperty("std.report_location");
logger.info(" basepath " + basePath);
connection=ConnectionManager.getConnection();
StandardReportsForm standardReportsForm=(StandardReportsForm)form;
filePaths=standardReportsForm.getFilePath();
logger.info("filepaths " + filePaths);
ServletOutputStream fos = null;
InputStream is = null;
String [] filePathArr = filePaths.split(",");
FileIO fio = null;
FileIO srcFio = null;
if (filePathArr.length > 1) {
filePath = filePathArr[0].substring(0,filePathArr[0].lastIndexOf("."))+".zip";
logger.info(filePath + " creating zip file ......");
directory = basePath+filePath.substring(0,filePath.lastIndexOf('/'));
logger.info( " Direcory Name :" +directory);
fileName = filePath.substring(filePath.lastIndexOf('/')+1);
logger.info( " File Name :" +fileName);
fio = new FileIO(directory,fileName);
fio.mkDir();
byte[] buffer = new byte[1024];
OutputStream fosForZip = fio.createOutputStream();
ZipOutputStream zos = new ZipOutputStream(fosForZip);
InputStream fis = null;
for (int i=0; i < filePathArr.length; i++) {
srcFileName = filePathArr[i].substring(filePathArr[i].lastIndexOf('/')+1);
srcFio = new FileIO(directory,srcFileName);
if (srcFio.isFileExist()) {
cont=true;
logger.info(" adding into zip file " +srcFileName);
fis = srcFio.createInputStream();
BufferedInputStream bis = new BufferedInputStream(fis);
zos.putNextEntry(new ZipEntry(srcFileName));
int length;
while ((length = bis.read(buffer)) != -1) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
// close the InputStream
bis.close();
srcFio.closeInputStream(fis);
} else {
logger.info(srcFileName + " file does not exist on shared drive");
cont =false;
break;
}
}
FileIO.closeOutputStream(zos);
if (!cont){
standardReportsForm.setMissingFileName(srcFileName);
request.getSession().getAttribute("fetchReports");
standardReportsForm.setFetchedReports((List<ReportDetails>)request.getSession().getAttribute("fetchReports"));
return mapping.findForward("fetchReport");
}
} else {
filePath = filePathArr[0];
fileName = filePath.substring(filePath.lastIndexOf('/')+1);
}
if (basePath.startsWith("smb")) {
SmbFile smbFile = new SmbFile(basePath+filePath,SMBHelper.getInstance().createAuthFromSmbLocation(basePath));
if(smbFile.exists())
{
is = new SmbFileInputStream(smbFile);
cont=true;
}
} else {
File file=new File(basePath+filePath);
if(file.exists())
{
is = new FileInputStream(file);
cont=true;
}
}
if(cont)
{
fos=response.getOutputStream();
setContentType(response, fileName);
//fos.write (baos.toByteArray());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for (int readNum; (readNum = is.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
}
byte[] bytes = bos.toByteArray();
fos.write(bytes);
fos.flush();
fos.close();
} else {
standardReportsForm.setMissingFileName(fileName);
request.getSession().getAttribute("fetchReports");
standardReportsForm.setFetchedReports((List<ReportDetails>)request.getSession().getAttribute("fetchReports"));
return mapping.findForward("fetchReport");
}
}catch(SQLException sx) {
logger.error(" error log SQLException " ,sx);
failureList.add(new UROCException(UROCMessages.getMessage("ERR_CONN_EXEC"), sx));
} catch(NamingException ne) {
logger.info("RMI error is "+ne);
failureList.add(new UROCException(UROCMessages.getMessage("ERR_NAMING_EXEC"), ne));
} catch(Exception e) {
logger.error(" error log Exception " ,e);
failureList.add(new UROCException(UROCMessages.getMessage("ERR_GEN_EXEC", new String[] {"General Exception"}), e));
} finally {
SQLHelper.closeConnection(connection, failureList, logger);
}
return null;
}
yah you can use java code to unzip the file.here is the example
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipUtility {
public String zipFilePath= "D:/javatut/corejava/src/zipfile.zip";
public String destDir = "D:/javatut/corejava";
private static final int BUFFER_SIZE = 4096;
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
UnzipUtility uu = new UnzipUtility();
uu.unzip(uu.zipFilePath, uu.destDir);
}
public void unzip(String zipFilePath,String destDir)throws IOException{
File destDirectory = new File(destDir);
if(!destDirectory.exists()){
destDirectory.mkdir();
}
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry zipEntry = zipIn.getNextEntry();
while(zipEntry!=null){
String filePath=destDir+File.separator+zipEntry.getName();
if(!zipEntry.isDirectory()){
extractFile(zipIn,filePath);
}
else{
File dir = new File(filePath);
dir.mkdir();
}
zipIn.closeEntry();
zipEntry = zipIn.getNextEntry();
}
zipIn.close();
}
private void extractFile(ZipInputStream zipIn, String filePath) throws FileNotFoundException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;
try {
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
thank you.......
please follow this path and (clear) automatic files viewer
chrome://settings/onStartup/Advanced/Downloads/automatic file viewer (clear)
I've to upload a zip file to ftp server, And here zip file also constructing dynamically.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipOutputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
public class CommonsNet {
public static void main(String[] args) throws Exception {
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("127.0.0.1");
client.login("phani", "phani");
String filename = "D://junk.pdf";
fis = new FileInputStream(new File(filename));
byte[] bs = IOUtils.toByteArray(fis);
fis.close();
OutputStream outputStream = client.storeFileStream("remote.zip");
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
zipOutputStream.setLevel(ZipOutputStream.STORED);
addOneFileToZipArchive(zipOutputStream,
"junk.pdf", bs);
zipOutputStream.close();
outputStream.close();
client.logout();
System.out.println("Transfer done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void addOneFileToZipArchive(ZipOutputStream zipStream,
String fileName, byte[] content) throws Exception {
ZipArchiveEntry zipEntry = new ZipArchiveEntry(fileName);
zipStream.putNextEntry(zipEntry);
zipStream.write(content);
zipStream.flush();
zipStream.closeEntry();
}
}
After executing this code the file is successfully created but i am unable to open a file inside archive.
like :
! D:\phani\remote.zip: The archive is corrupt
! D:\phani\remote.zip: Checksum error in C:\Users\BHAVIR~1.KUM\AppData\Local\Temp\Rar$DIa0.489\MCReport.pdf. The file is corrupt
Try adding client.setFileType(FTP.BINARY_FILE_TYPE); just after you have logged in.
I remember that default transfer mode is ASCII, so non-ascii files may result corrupted.
I have zip file which is inside a folder in zip file please suggest me how to read it using zip input stream.
E.G.:
abc.zip
|
documents/bcd.zip
How to read a zip file inside zip file?
If you want to look through zip files within zip files recursively,
public void lookupSomethingInZip(InputStream fileInputStream) throws IOException {
ZipInputStream zipInputStream = new ZipInputStream(fileInputStream);
String entryName = "";
ZipEntry entry = zipInputStream.getNextEntry();
while (entry!=null) {
entryName = entry.getName();
if (entryName.endsWith("zip")) {
//recur if the entry is a zip file
lookupSomethingInZip(zipInputStream);
}
//do other operation with the entries..
entry=zipInputStream.getNextEntry();
}
}
Call the method with the file input stream derived from the file -
File file = new File(name);
lookupSomethingInZip(new FileInputStream(file));
The following code snippet lists the entries of a ZIP file inside another ZIP file. Adapt it to your needs. ZipFile uses ZipInputStreams underneath the hood.
The code snippet uses Apache Commons IO, specifically IOUtils.copy.
public static void readInnerZipFile(File zipFile, String innerZipFileEntryName) {
ZipFile outerZipFile = null;
File tempFile = null;
FileOutputStream tempOut = null;
ZipFile innerZipFile = null;
try {
outerZipFile = new ZipFile(zipFile);
tempFile = File.createTempFile("tempFile", "zip");
tempOut = new FileOutputStream(tempFile);
IOUtils.copy( //
outerZipFile.getInputStream(new ZipEntry(innerZipFileEntryName)), //
tempOut);
innerZipFile = new ZipFile(tempFile);
Enumeration<? extends ZipEntry> entries = innerZipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
System.out.println(entry);
// InputStream entryIn = innerZipFile.getInputStream(entry);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// Make sure to clean up your I/O streams
try {
if (outerZipFile != null)
outerZipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
IOUtils.closeQuietly(tempOut);
if (tempFile != null && !tempFile.delete()) {
System.out.println("Could not delete " + tempFile);
}
try {
if (innerZipFile != null)
innerZipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
readInnerZipFile(new File("abc.zip"), "documents/bcd.zip");
}
Finally got it to work fixing Manas Maji's answer. Minimal solution:
import java.io.*;
import java.nio.file.*;
import java.util.zip.*;
import org.slf4j.*;
public void readZipFileRecursive(final Path zipFile) {
try (final InputStream zipFileStream = Files.newInputStream(zipFile)) {
this.readZipFileStream(zipFileStream);
} catch (IOException e) {
LOG.error("error reading zip file %s!", zipFile, e);
}
}
private void readZipFileStream(final InputStream zipFileStream) {
final ZipInputStream zipInputStream = new ZipInputStream(zipFileStream);
ZipEntry zipEntry;
try {
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
LOG.info("name of zip entry: {}", zipEntry.getName());
if (!zipEntry.isDirectory() && zipEntry.getName().endsWith(".zip")) {
this.readZipFileStream(zipInputStream); // recursion
}
}
} catch (IOException e) {
LOG.error("error reading zip file stream", e);
}
}
Care: don't close stream in recursive method.
I have written a code that can unzip all zip files inside a zip file. It can even unzip to n levels of compression. Like for example if you had a zip file inside a zip, inside a zip ( and so on) it would extract all of them. Use the zipFileExtract method of this class and pass the source zip file and destination directory as an argument.
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class RecursiveFileExtract {
private static final int BUFFER_SIZE = 4096;
private static Queue<File> current;
private static List<File> visited;
public static void zipFileExtract(File sourceZipFile, File destinationDirectory) {
Path temp = null;
if(!destinationDirectory.exists())
{
destinationDirectory.mkdirs();
}
try {
temp = Files.move(Paths.get(sourceZipFile.getAbsolutePath()), Paths.get(destinationDirectory.getAbsolutePath()+File.separator+sourceZipFile.getName()));
} catch (IOException e) {
e.printStackTrace();
}
File zipFile = new File(temp.toAbsolutePath().toString());
current = new ConcurrentLinkedQueue<>();
visited = new ArrayList<>();
current.add(zipFile);
do {
unzipCurrent();
zipFinder(destinationDirectory);
}
while (!current.isEmpty());
}
private static void zipFinder(File directory) {
try {
if (directory != null) {
File fileArray[] = directory.listFiles();
if (fileArray != null) {
for (File file : fileArray) {
if (file != null) {
if (file.isDirectory()) {
zipFinder(file);
} else {
if (file.getName().endsWith(".zip")) {
if (!visited.contains(file)) {
current.add(file);
}
}
}
}
}
}
}
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
}
private static void unzipCurrent() {
try {
while (!current.isEmpty()) {
File file = current.remove();
visited.add(file);
File zipDirectory = new File(file.getParentFile().getAbsolutePath());
unzip(file.getAbsolutePath(), zipDirectory.getAbsolutePath());
}
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
}
public static void unzip(String zipFilePath, String destDirectory) {
try {
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry entry = zipIn.getNextEntry();
while (entry != null) {
String filePath = destDirectory + File.separator + entry.getName();
if (!entry.isDirectory()) {
extractFile(zipIn, filePath);
} else {
File dir = new File(filePath);
Boolean result = dir.mkdir();
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
zipIn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void extractFile(ZipInputStream zipIn, String filePath) {
try {
File file = new File(filePath);
File parentFile = file.getParentFile();
if (!parentFile.exists()) {
Boolean result = parentFile.mkdirs();
if (!result) {
throw new Exception();
}
}
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.close();
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
}
}