Java file manipulation--2 (zip file release)

Source: Internet
Author: User
Tags array contains file size readfile readline relative zip

In Java, there is a special package for the operation of the zip file (java.util.zip), the zip file is very convenient to operate, the last time to write a ZIP file release program, spent a day finally finished, At first it was quite simple: the principle was to get the folders and files in the zip file through Zipinputstream and ZipEntry class one by one, and then create the files and folders in the corresponding directories respectively. But the realization is not the case, and there are a lot of details are difficult to resolve, which in the call Zipinputstream in the Getnextentry method when the zip file contains the Chinese pathname or file name will throw an exception, So this procedure will inevitably have a lot of mistakes and bugs, and even some ideas on the issue, I hope we can make more comments.
In fact, the operation of the file in Java is to the input and output flow of the use and control, so that some fan, but if you understand the flow of the application will feel that the file operation is so! But you must not think that the Java input and output is so simple, will use and use good is two different things, like the same description of the idea of resolute, decisive and arbitrary is two distinct descriptions, so to use a good Java access and output still need a lot of practice, a lot of thinking. Well, said so much is some nonsense, the following is the source of the program, hope for everyone useful!
Pcera
2005-7-2 17:44

/**
* Class Name: Zipfilerelease
* Description: Zip file decompression, release in the specified, directory
* Introduction: The main ZIP file release method ReleaseHandle ()
* Use the Zipinputstream class and the ZipEntry class to enumerate the entry lists for the zip file, and then
* Based on the user-supplied output path and zip file entry for combination through DataOutputStream
* and the file class to create files and directories, file data is created by
* A nested combination of Zipinputstream class, ZipEntry class, InputStream class is obtained.
* Note: If the zip file contains the Chinese path program will throw an exception
* Date: 2005-7-1
* Author: Pcera
*/

Import java.io.*;
Import java.util.*;
Import java.util.zip.*;

Class zipfilerelease{

Private String Infilepath;
Private String Releasefilepath;
Private string[] Filenamearray; An array that holds the name of the file
Private ZipEntry entry;
//
Private FileInputStream Filedatain;
Private FileOutputStream filedataout;
Private Zipinputstream Zipinfile;
Private DataOutputStream WriteData;
Private DataInputStream ReadData;
//
private int zipfilecount = 0; Total number of files in zip file
private int zippathcount = 0; Total number of paths in zip file

/**
* Initialization function
* Initialization of the zip file stream, output file stream, and other variables
*/
Public Zipfilerelease (String inpath,string releasepath) {
Infilepath = Inpath;
Releasefilepath = Releasepath;
}

/**
* Initialize read file stream function
* Parameter: FileInputStream class
* Return value: Initialize successfully return 0, otherwise return-1
*/
Protected long Initinstream (Zipinputstream Zipfilea) {
try{
ReadData = new DataInputStream (Zipfilea);
return 0;
}catch (Exception e) {
E.printstacktrace ();
return-1;
}
}

/**
* Test File path
* Parameter: The path to the zip file and the location to release
* Return value: Two-bit integer, 10 digits in two digits represent input path and output path (1 input, 2 output)
* Each number represents an absolute or relative path (1 absolute, 0 relative)
* Return-1 means the path is invalid

Protected long Checkpath (String inpath,string outpath) {
File infile = new file (Inpath);
File infile = new file (Outpath);

}
*/

/**
* Initialize output file stream
* Parameters: File class
* Return value: Initialize successfully return 0, otherwise return-1
*/
Protected long Initoutstream (String Outfilea) {
try{
Filedataout = new FileOutputStream (Outfilea);
WriteData = new DataOutputStream (filedataout);
return 0;
}catch (IOException e) {
E.printstacktrace ();
return-1;
}
}

/**
* Test File Exists method
* Parameters: File class
* Return value: Returns 1 if file size is returned
*/
Public long Checkfile (File Infilea) {
if (infilea.exists ()) {
return 0;
}else{
return-1;
}
}

 /**
  * Determine if the file can read the method
  * Parameters: File class
  * return value: If can read return 0, otherwise return-1
  */
  Public long Checkopen (File Infilea) {
  if (Infilea.canread ()) {
   return infilea.length ();
 }else{
   return-1;
 }
 }

 /**
  * Get the total number of folders and files in the zip file
  * Parameters: File class
  * return value: Return the total if normal, otherwise return-1
  */
 public Long Getfilfoldcount (String Infilea) {
  try{
   int filecount = 0;
   zipinfile = new Zipinputstream (
      new FileInputStream (Infilea));
   while ((entry = Zipinfile.getnextentry ())!= null) {
    if (entry.isdirectory ()) {
& nbsp;    zippathcount++;
   }else{
     zipfilecount++
   }
    filecount++;
  }
   return filecount;
 }catch (IOException e) {
   e.printstacktrace ();
   return-1;
 }
 }

/**
* Read the zip file manifest function
* Parameters: File class
* Return value: File list array
*/
Public string[] Getfilelist (String Infilea) {
try{
Zipinputstream azipinfile = new Zipinputstream (
New FileInputStream (Infilea));
Creating an Array Object
Filenamearray = new string[(int) getfilfoldcount (Infilea)];

Passing the file name list to an array
int i = 0;
while ((entry = Azipinfile.getnextentry ())!= null) {
filenamearray[i++] = Entry.getname ();
}
return filenamearray;
}catch (IOException e) {
E.printstacktrace ();
return null;
}
}

 /**
  * Create file Functions
  * Parameters: File class
  * return value: If the creation succeeds return 0, otherwise return-1
  */
 public Long WriteFile (String outfilea,byte[] databyte) {
  try{
   if (initoutstream (outfilea) = = 0) {
    Writedata.write (Databyte);
    filedataout.close ();
    return 0;
  }else{
    filedataout.close ();
    return-1;
  }
 }catch (IOException e) {
   e.printstacktrace ();
   return-1;
 }
 }

 /**
  * Read the file content function
  * Parameters: File class
  * Return value: Returns a byte array to read data if the fetch succeeds, or null if it fails
  */
 protected byte[]
 readfile (zipentry entrya,zipinputstream Zipfilea) {
  try{
   Long Entryfilelen;
   if (initinstream (zipfilea) = = 0) {
    if (Entryfilelen = Entrya.getsize ()) >= 0) {
     byte[] entryfiledata = new byte[(int) Entryfilelen];
     readdata.readfully (entryfiledata,0, (int) entryfilelen);
     return entryfiledata;
   }else{
     return null;
   }
  }else{
    return null;
  }
 }catch (IOException e) {
   e.printstacktrace ();
   return null;
 }
 }

/**
* Create a directory function
* Parameter: The path to create the directory
* Return value: Returns 0 if the creation succeeds, otherwise returns-1
*/
Public Long CreateFolder (String dir) {
File File = new file (dir);
if (File.mkdirs ()) {
return 0;
}else{
return-1;
}
}

/**
* Delete File
* Parameters: Files to be deleted
* Return value: If the deletion succeeds then returns 0, the file to be deleted does not exist return-2
* If you want to delete a path, return-3, delete failure then return-1
*/
Public long DeleteFile (String Apath) throws SecurityException {
File File = new file (Apath.trim ());
File or path does not exist
if (!file.exists ()) {
Return-2;
}
The path to delete is a
if (!file.isfile ()) {
return-3;
}
Delete
if (File.delete ()) {
return 0;
}else{
return-1;
}
}

/**
* Delete Directory
* Parameter: Directory to delete
* Return value: Returns 0 if the deletion succeeds, or 1 if the deletion fails
*/
Public long DeleteFolder (String apath) {
File File = new file (Apath);
Delete
if (File.delete ()) {
return 0;
}else{
return-1;
}
}

/**
* Determine if the path you want to extract has a file with the same name
* Parameters: Decompression Path
* Return value: If there is a file with the same name return-1, otherwise return 0
*/
Public long checkpathexists (String areleasepath) {
File File = new file (Areleasepath);
if (!file.exists ()) {
return 0;
}else{
return-1;
}
}

/**
* Delete files in zip
* Parameters: File list array, releasing path
* Return value: If Delete succeeds return 0, otherwise return-1
*/
Protected
Long Deletereleasezipfile (string[] listfilepath,string releasepath) {
Long Arraylen,flagreturn;
int k = 0;
String TempPath;
Path to store zip file manifest
string[] Patharray = new String[zippathcount];
deleting files
Arraylen = Listfilepath.length;
for (int i=0;i< (int) arraylen;i++) {
TempPath = Releasepath.replace (' \ n ', '/') + listfilepath[i];
Flagreturn = DeleteFile (TempPath);
if (Flagreturn = = 2) {
Not doing anything.
}else if (Flagreturn = = 3) {
patharray[k++] = TempPath;
}else if (Flagreturn = = 1) {
return-1;
}
}
Delete Path
for (k = k-1;k>=0;k--) {
Flagreturn = DeleteFolder (Patharray[k]);
if (Flagreturn = = 1) return-1;
}
return 0;
}

/**
* Get the top-level folder name of the zip file
* Parameter: Zip file path
* Return Value: folder name, return NULL if failed
*/
public string Getziproot (string Infilea) {
String Rootname;
try{
FileInputStream tempfile = new FileInputStream (Infilea);
Zipinputstream azipinfile = new Zipinputstream (tempfile);
ZipEntry Aentry;
Aentry = Azipinfile.getnextentry ();
Rootname = Aentry.getname ();
Tempfile.close ();
Azipinfile.close ();
return rootname;
}catch (IOException e) {
E.printstacktrace ();
return null;
}
}

/**
* Releasing the stream, releasing the resource for consumption
*/
protected void Closestream () throws exception{
Filedatain.close ();
Filedataout.close ();
Zipinfile.close ();
Writedata.flush ();
}

/**
* Decompression function
* The user's zip file path and decompression path to determine whether to exist and open
* In the input decompression path, if input "/" in and zip files stored in the statistics directory for decompression
* Return Value: 0 indicates a successful release
*-1 indicates that the file you are trying to extract does not exist,
*-2 indicates that the file you are trying to extract cannot be opened,
*-3 The path you want to release does not exist,
*-4 The file directory you created failed,
*-5 failed to write to file,
*-6 indicates that the file you want to release already exists,
*-50 indicates a file read exception
*/
Public long ReleaseHandle () throws exception{
File InFile = new file (Infilepath);
File outfile = new file (Releasefilepath);
String Tempfile;
String Zippath;
String Ziprootpath;
String temppathparent; Store release Path
Byte[] Zipentryfiledata;

To make a valid judgment
if (checkfile (inFile) = =-1) {
return-1;}
if (Checkopen (inFile) = =-1) {
Return-2;}
It's not an extract. The validity test of the path in the current directory
if (!releasefilepath.equals ("/")) {
Unzip in user specified directory
if (checkfile (outfile) = =-1) {
return-3;}
}
Get the standard release path
if (!releasefilepath.equals ("/")) {
Temppathparent = releasefilepath.replace (' \ \ ', '/') + "/";
}else{
Temppathparent = Infile.getparent (). replace (' \ \ ', '/') + "/";
}
Get the entry list in the zip file
Filenamearray = Getfilelist (Infilepath);
Get the top-level directory of Zip files
Ziprootpath = Getziproot (Infilepath);
//
Filedatain = new FileInputStream (Infilepath);
Zipinfile = new Zipinputstream (filedatain);
Determine if the folder you want to release already exists
if (checkpathexists (Temppathparent +
Ziprootpath.substring (0,ziprootpath.lastindexof ("/")) = = = 1) {
return-6;
}
//
try{
Creating folders and Files
int i = 0;
while ((entry = Zipinfile.getnextentry ())!= null) {
if (Entry.isdirectory ()) {
Create a table of contents
Zippath = Temppathparent + filenamearray[i];
Zippath = zippath.substring (0,zippath.lastindexof ("/"));
if (CreateFolder (zippath) = =-1) {
Closestream ();
Deletereleasezipfile (filenamearray,temppathparent);
return-4;
}

  }else{
   //Read file data
    zipentryfiledata = readFile (Entry, Zipinfile);
   //write data to file
    tempfile = temppathparent + filenamearray[i];
   //write file
    if (WriteFile (tempfile,zipentryfiledata) = = 1) {
      Closestream ();
     Deletereleasezipfile (filenamearray,temppathparent);
     return-5;
   }
  }
   i++;
 }
 /Release Resources
  Closestream ();
  return 0;
 }catch (Exception e) {
   closestream ();
   Deletereleasezipfile (filenamearray,temppathparent);
   e.printstacktrace ();
   return-50;
 }
 }
 /**
  * Demo function
  * Extract files based on user input
  */
 public static void Main (String args[] ) throws Exception {

Long Flag; Return flag
String Inpath,releasepath;

Get user input information
BufferedReader userinput = new BufferedReader (
New InputStreamReader (system.in));
System.out.println ("Please enter zip file path:");
Inpath = Userinput.readline ();
System.out.println ("Please enter save path:");
Releasepath = Userinput.readline ();
Userinput.close ();

Perform decompression
Zipfilerelease pcerazip = new Zipfilerelease (Inpath,releasepath);
Flag = Pcerazip.releasehandle ();

Error message Printing
if (flag = 0) System.out.println ("Release success!!! ");
if (flag = = 1) System.out.println ("The file you are trying to extract does not exist!") ");
if (flag = = 2) System.out.println ("The file you want to extract cannot be opened!") ");
if (flag = = 3) System.out.println ("The path you want to release does not exist!") ");
if (flag = = 4) System.out.println ("The file directory you created failed!") ");
if (flag = = 5) System.out.println ("Write file failed!") ");
if (flag = = 6) System.out.println ("File already exists!") ");
if (flag = = -50) System.out.println ("file read exception!)" ");
}
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.