Java stream classes : How to make a win zip Application - java

I want to make a win zip software. I am reading java stream classes and zip class but my mind can't work in this topic. Please help me How to do this. This my minor project in my college. I made two project in java.
Library management System
Diagnostic Lab Management
But Teacher say Management project not allowed. Please help me
This code work in one directory make for multidirectory
My Program Code
import java.io.*;
import java.util.*;
import java.util.zip.*;
import java.util.*;
import java.io.*;
class MyZip{
FileInputStream fis;
BufferedInputStream bis;
FileOutputStream fos;
BufferedOutputStream bos;
ZipOutputStream zout;
ZipEntry ze;
public MyZip()throws IOException{
Console con=System.console();
System.out.println("How many directories do u want to compressed:");
int no_file=Integer.parseInt(con.readLine());
String inputFile[]=new String[no_file];
File fileArray[]=new File[no_file];
System.out.println("Enter the path of directories to be compressed:");
for(int i=0;i<inputFile.length;i++){
inputFile[i]=con.readLine();
fileArray[i]=new File(inputFile[i]);
}
String outputFile="E:\\MyProgram\\MyZip\\MyZip.zip";
fos=new FileOutputStream(outputFile);
bos=new BufferedOutputStream(fos);
zout=new ZipOutputStream(bos);
zipFile(fileArray);
zout.close();
bos.close();
fos.close();
getZipEntry();
}
public void getZipEntry()throws IOException{
ZipFile zf=new ZipFile("E:\\MyProgram\\MyZip\\MyZip.zip");
System.out.println(zf.getName());//return name of zip file
Enumeration e=zf.entries();
while(e.hasMoreElements()){
ZipEntry ze=(ZipEntry)e.nextElement();
System.out.print(ze.getName()+"\t");//return name of entry
System.out.print(ze.getSize()+"\t");//return uncompressed size
System.out.print(ze.getCompressedSize());//return compressed size
System.out.println();
}
zf.close();
}
public void zipFile(File farr[])throws IOException{
for(File f:farr){
if(f.isFile()){
writeFile(f);
}
if(f.isDirectory()){
File fileArray[]=f.listFiles();
zipFile(fileArray);
}
}
}
public void writeFile(File f)throws IOException{
ze=new ZipEntry(f.getPath());
zout.putNextEntry(ze);
fis=new FileInputStream(f);
bis=new BufferedInputStream(fis);
int ch;
while((ch=bis.read())!=-1)
zout.write(ch);
bis.close();
fis.close();
zout.closeEntry();
zout.flush();
}
public static void main(String args[]) throws IOException{
new MyZip();
}
}

Use for unzip your code only for zip
import java.io.*;
import java.util.*;
import java.util.zip.*;
class MyUnZip
{
FileInputStream fis;
BufferedInputStream bis;
ZipInputStream zis;
FileOutputStream fos;
BufferedOutputStream bos;
public MyUnZip(String inputFile)throws IOException{
String path1=inputFile.substring(0,inputFile.lastIndexOf('.'));
//System.out.println(path1);
fis=new FileInputStream(inputFile);
bis=new BufferedInputStream(fis);
zis=new ZipInputStream(bis);
File outputFile;
ZipEntry ze=null;
while((ze=zis.getNextEntry())!=null){
String str=ze.getName();
//System.out.println(str);
File fileName=new File(str);
String path2=str.substring(str.indexOf('\\'),str.lastIndexOf('\\'));
//System.out.println(path2);
String path3=path1+path2;
System.out.println(path3);
File filePath=new File(path3);
filePath.mkdirs();
outputFile=new File(path3,fileName.getName());
fos=new FileOutputStream(outputFile);
bos=new BufferedOutputStream(fos);
int ch;
while((ch=zis.read())!=-1)
bos.write(ch);
bos.close();
fos.close();
zis.closeEntry();
}
zis.close();
}
public static void main(String args[]) throws IOException{
Console con=System.console();
System.out.println("Enter the path of zip file to be uncompressed:");
String inputFile=con.readLine();
new MyUnZip(inputFile);
}
}

Related

Unable to delete specific files after unzipping the files

Am new to Java, I searched in google for unzipping the files. Tested the code in my local and am able to unzip the files.
But unable to delete the files I tried some logic but no luck.
Can anyone help me how read a particular file and delete that file using its path and also need to delete a specific folder using its path and delete recursively. all the other files need to be there
Below is the code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipFiles {
public static void main(String[] args) {
String zipFilePath = "/Users/Safeer_Pasha/Music/archive.zip";
String destDir = "/Workspace/";
unzip(zipFilePath, destDir);
}
private static void unzip(String zipFilePath, String destDir) {
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);
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry ze = zis.getNextEntry();
while(ze != null){
String fileName = ze.getName();
File newFile = new File(destDir + File.separator + fileName);
System.out.println("Unzipping to "+newFile.getAbsolutePath());
//create directories for sub directories in zip
new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
//close this ZipEntry
zis.closeEntry();
ze = zis.getNextEntry();
}
//close last ZipEntry
zis.closeEntry();
zis.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Cannot open generated zip file

I've followed several articles to create a zip file using java ZipOutputStream class. The zip is created but I cannot open it. On my Mac I'm receiving this message when I open it with the unzip command :
End-of-central-directory signature not found. Either this file is not
a zipfile, or it constitutes one disk of a multi-part archive. In the
latter case the central directory and zipfile comment will be found on
the last disk(s) of this archive.
unzip: cannot find zipfile
directory in one of /Users/xxxx/Downloads/iad.zip or
/Users/xxxx/Downloads/iad.zip.zip, and cannot find /Users/xxxx/Downloads/iad.zip.ZIP, period.
My java class :
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static java.util.Arrays.stream;
#Slf4j
#UtilityClass
public class ZipCreator {
public byte[] compressAll(String... files) throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zipOut = new ZipOutputStream(baos)) {
stream(files)
.forEach(file -> addToZip(zipOut, file));
return baos.toByteArray();
}
}
private static void addToZip(ZipOutputStream zipOut, String file) {
File fileToZip = new File(file);
try (FileInputStream fis = new FileInputStream(fileToZip.getCanonicalFile())) {
zipOut.putNextEntry(new ZipEntry(fileToZip.getName()));
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
} catch (IOException e) {
log.error("Error when adding file {} to zip", file, e);
}
}
}
Doas anyone have an idea to get this zip open ?
You forgot to call closeEntry(). And you should call close() for ZipOutputStream before baos.toByteArray():
public static byte[] compressAll(String... files) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zipOut = new ZipOutputStream(baos)) {
stream(files).forEach(file -> addToZip(zipOut, file));
}
return baos.toByteArray();
}
private static void addToZip(ZipOutputStream zipOut, String file) {
File fileToZip = new File(file);
try (FileInputStream fis = new FileInputStream(fileToZip.getCanonicalFile())) {
zipOut.putNextEntry(new ZipEntry(fileToZip.getName()));
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
zipOut.closeEntry();
} catch (IOException e) {
log.error("Error when adding file {} to zip", file, e);
}
}
For ByteArrayOutputStream you must close ZipOutputStream before retrieve byte array from ByteArrayOutputStream.
For FileOutputStream is the same. You must close ZipOutputStream before closing FileOutputStream. Note that the close methods of resources are called in the opposite order of their creation.
public static void compressAll(String... files) throws IOException {
try (FileOutputStream fos = new FileOutputStream("test.zip");
ZipOutputStream zipOut = new ZipOutputStream(fos)) {
stream(files).forEach(file -> addToZip(zipOut, file));
}
}

Can't write file to zip

I try to put some file fileNamePath in zip archive (arguments are D:\text.txt D:\archive.zip):
public static void main(String[] args) throws IOException {
if (args.length==0) return;
String fileNamePath = args[0];
String zipPath = args[1];
FileOutputStream outputStream = new FileOutputStream(zipPath);
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
zipOutputStream.putNextEntry(new ZipEntry(fileNamePath));
File file = new File(fileNamePath);
Files.copy(file.toPath(),zipOutputStream);
zipOutputStream.closeEntry();
zipOutputStream.close();
}
Archive is created but i don't see any file in it. Why?
That code is working perfectly:
zip.java
import java.io.*;
import java.nio.file.*;
import java.util.zip.*;
public class zip
{
public static void main(String[] args) throws IOException {
if (args.length==0) return;
String fileNamePath = args[0];
String zipPath = args[1];
FileOutputStream outputStream = new FileOutputStream(zipPath);
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
zipOutputStream.putNextEntry(new ZipEntry(fileNamePath));
File file = new File(fileNamePath);
Files.copy(file.toPath(),zipOutputStream);
zipOutputStream.closeEntry();
zipOutputStream.close();
}
}
I have compiled it under Debian 9 Stretch, OpenJDK 8
I have then created a sample txt file:
hello.txt
Hello World
I then compiled it:
javac zip.java
And finally run it:
java zip hello.txt hello.zip
I extract the .zip and open up hello.txt, returning Hello World
May it be that you have no permissions to read/write D:\?

how to create zip inside the other zip.i got the fileNotFoundException

How to create zip inside zip file
enter image description here
got bellow Error:
D:\sagar\my work\Package Maker\DirectoryStruct>java zipStructure
java.io.FileNotFoundException: Additional_Sub_Folder\Additional_file.zip (The sy
stem cannot find the path specified)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
at java.io.FileOutputStream.<init>(FileOutputStream.java:110)
at zipStructure.main(zipStructure.java:22)
D:\sagar\my work\Package Maker\DirectoryStruct> that is Additional_sub_folder and Digital_sub_folder. inside Additional_sub_folder 1 zip file created(Additional_file.zip),inside that zip 2 folder are created like xml folder and pdf folder
and inside Digital_sub_folder create Artical_sub_folder,and inside Artical_sub_folder 3 new folder are created that is xml folder,pdf folder and Graphics folder. i try it be below java code but not works properly,please help to create the this structure.
import java.io.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class zipStructure {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("main.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
zos.putNextEntry(new ZipEntry("Additional_Sub_Folder/"));
zos.putNextEntry(new ZipEntry("Digital_Sub_Folder/"));
FileOutputStream fos1 = new FileOutputStream("Additional_Sub_Folder/Additional_file.zip");
ZipOutputStream zos1 = new ZipOutputStream(fos1);
/*zos1.putNextEntry(new ZipEntry("Additional_file.zip/xml/"));
zos1.putNextEntry(new ZipEntry("Additional_file.zip/pdf/"));*/
zos1.putNextEntry(new ZipEntry("Additional_file1.zip/xml/"));
zos1.putNextEntry(new ZipEntry("Additional_file1.zip/pdf/"));
zos1.close();
fos1.close();
zos.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void addToZipFile(String fileName, ZipOutputStream zos) throws FileNotFoundException, IOException {
System.out.println("Writing '" + fileName + "' to zip file");
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(fileName);
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
fis.close();
}
}
[1]: http://i.stack.imgur.com/TNA8b.jpg
I did not have the problem with the zip-I/O, I had the FileNotFoundException with every type of I/O that uses the fileSystem.
What helped for me was, if you're working with eclipse, that there is function like "refresh project" or something like this. Everytime I had problems with I/O, that worked.

Download files from the web server by java

I would like to download the temp files from an web server
The code i tried is below, but i am getting only the HTML content being written the ouput file
But the url path contains 712 files in .gz format
This is the code I am using:
import java.io.*;
public class SampleFile{
public static void main(String args[]) throws IOException{
BufferedInputStream in = new BufferedInputStream(new java.net.URL("http://xxx:9080/xxx/xxx/xxx/xxx/xxx.jsp?file=/apps/WasApps/xxx/templogs/xxx.log.xxx_Server1.2012-04-01.gz").openStream());
FileOutputStream fos = new FileOutputStream("LocalPath\\koushik.txt");
BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
int x=0;
byte[] data = new byte[1024];
while((x=in.read(data,0,1024))>=0) {
bout.write(data,0,x);
}
bout.close();
in.close();
}
}

Categories

Resources