Java Learning notes: Use the Zip API for file decompression and to read directly the contents of the specified file

Source: Internet
Author: User
Tags extract zip file mkdir pack parent directory

Using Zip for file transfer in an Android project can greatly reduce storage space and transfer traffic, so it involves compressing the zip file. The Java Native Zip API is described in detail below. First, a simple list of Java in the API on the zip: first , zip compression

Java creates an output stream from a zipoutputstream to a zip file, and you can use the following construction methods:

FileOutputStream fos = new FileOutputStream (outfile);
Zipoutputstream Zos = new Zipoutputstream (FOS);

After creating the output stream for the zip file, we need to write one by one to the file that needs to be compressed, through the Zipoutputstream putnextentry (zipentry E) method, You can create a "portal" of the next file you want to write in the build zip file.

ZipEntry can call its constructor zipentry (String name) to make a name for the file to be written, which contains the subdirectory of the file relative to the zip file.

Examples are as follows:

If we want to package the T.txt file into a zip file and are packaged into the "dir" folder in the zip file, then you need to specify the name of its zipentry constructor as "Dir/t.txt". If you are packing directly into a level-one directory in a zip file, you just need to specify name "T.txt".

Here's a piece of code to compress a file into a zip:


Ze = new ZipEntry (subpath);
Zos.putnextentry (ze);
bis = new Bufferedinputstream (new FileInputStream (f));
while (Bis.read (data, 0, ByteLength)!=-1) {
	zos.write (data);
}
Bis.close ();
Zos.closeentry ();



In the code above, Subpath is the directory + name of the compressed file in the zip file, and each time you open a zipentry, you need to close the zipentry after the write/read operation is complete. The method of writing files to a zip file is the same as a normal write file, using Bufferedinputstream for the byte stream write operation. If you are compressing a directory, compress the file enumeration in the directory and specify its parent directory in ZipEntry's name.

The complete ZIP code is given below:


public class Ziploader {static int bytelength = 1024;  
	 Public Ziploader () {}/** * compressed file * @param files/directories that need to be compressed @param the name of the compressed output ZIP file * @return Whether the compression was successful * @throws FileNotFoundException * @throws IOException/public static Boolean zip (file[] files, String outfile)
		Throws FileNotFoundException, ioexception{file File = new file (outfile);
		String Zippath = File.getabsolutepath ();
		Zippath = zippath.substring (0, Zippath.length ()-file.separator.length ()-outfile.length ());
		Create a compressed file if (!file.exists ()) {file.createnewfile ();
		FileOutputStream fos = new FileOutputStream (outfile);
		Zipoutputstream Zos = new Zipoutputstream (FOS);
		
		Compressed pack (Zippath, files, Zos);
		Zos.flush ();
		Zos.close ();
	return true; /** * Package File/directory * @param srcpath ZIP file absolute path * @param files to be packaged file/directory * @param zos Zip input stream instance connected to the zip file * @throw S FileNotFoundException * @throws ioexception * * private static void Pack (String srcpath, file[) filES, Zipoutputstream zos) throws FileNotFoundException, IOException {Bufferedinputstream bis;
		ZipEntry ze;
		
		byte[] data = new Byte[bytelength];
			for (File f:files) {//Recursive compressed directory if (F.isdirectory ()) {Pack (Srcpath, F.listfiles (), Zos); else if (F.getname (). IndexOf ().
			Ds_store ")!=-1) {continue;
				else {//Get the path String subpath = F.getabsolutepath () of the compressed file relative to the zip file;
				int index = Subpath.indexof (Srcpath);
				if (index!=-1) {subpath = Subpath.substring (Srcpath.length () +file.separator.length ());
				}//Compressed file Ze = new ZipEntry (subpath);
				Zos.putnextentry (Ze);
				bis = new Bufferedinputstream (new FileInputStream (f));
				while (Bis.read (data, 0, ByteLength)!=-1) {zos.write (data);
				} bis.close ();
			Zos.closeentry (); }
		}
	}
}

The Zip method in the above Ziploader class is to invoke the pack method for zip compression, and in the pack method, if the file to be compressed is a directory, then a pack recursive call is made to the file in that directory.


second, zip decompression

ZipFile provides a entries () method to get the ZipEntry enumeration of the zip file, and then it can get the directory and filename of its relative zip file according to the ZipEntry GetName () method, and then through the Bufferedoutputstream and Bufferedinputstream read and write files can be.

	/** * Extract zip file * @param zipfile zip file object to extract * @param unzipfilepath Decompression Destination Absolute path * @throws IOException * * @SuppressW Arnings ("unchecked") public static void unzip (File zipfile, String unzipfilepath) throws IOException {ZipFile zip = NE
		W ZipFile (ZipFile);
		enumeration<zipentry> entries = (enumeration<zipentry>) zip.entries ();
		ZipEntry ze;
		String Unzipentrypath;
		String Unzipentrydirpath;
		int index;
		File Unzipentrydir;
		Bufferedoutputstream Bos;
		Bufferedinputstream bis;
		
		byte[] data = new Byte[bytelength];
		Create the unpacked folder file Unzipdir = new file (Unzipfilepath);
		if (!unzipdir.exists () | | |!unzipdir.isdirectory ()) {Unzipdir.mkdir ();
			//extract while (Entries.hasmoreelements ()) {//Get next extract file Ze = (zipentry) entries.nextelement ();
			Unzipentrypath = Unzipfilepath + File.separator + ze.getname ();
			index = Unzipentrypath.lastindexof (file.separator); Gets the uncompressed file upper level directory if (index!=-1) {Unzipentrydirpath = Unzipentrypath.substriNg (0, index);
			else {Unzipentrydirpath = "";
			///create uncompressed file upper Directory Unzipentrydir = new file (Unzipentrydirpath);
			if (!unzipentrydir.exists () | | |!unzipentrydir.isdirectory ()) {Unzipentrydir.mkdir ();
			//write out the extracted file Bos = new Bufferedoutputstream (new FileOutputStream (Unzipentrypath));
			bis = new Bufferedinputstream (Zip.getinputstream (Ze));
			while (Bis.read (data, 0, ByteLength)!=-1) {bos.write (data);
			} bis.close ();
			Bos.flush ();
		Bos.close ();
	} zip.close (); }

third, the puzzled pressure directly read the contents of the specified file within the zip file

With the second part of the code to break down, it is not difficult to read the contents of the specified file, directly on the code.

	/**
	 * Read the contents of the file in the zip file
	 * @param zipfile target zip file object
	 * @param readfilename target Read file name
	 * @return File content
	 * Throws Zipexception
	 * @throws ioexception * * *
	@SuppressWarnings ("unchecked") public
	static String Getzipfilecontent (File zipfile, String readfilename) throws Zipexception, IOException {
		StringBuilder content = new StringBuilder ();
		ZipFile zip = new ZipFile (zipfile);
		enumeration<zipentry> entries = (enumeration<zipentry>) zip.entries ();
		
		ZipEntry ze;
		The file in the enumeration zip file/While
		(Entries.hasmoreelements ()) {
			ze = entries.nextelement ();
			Reads the target object
			if (Ze.getname (). Equals (Readfilename)) {
				Scanner Scanner = new Scanner (Zip.getinputstream (Ze));
				while (Scanner.hasnextline ()) {
					content.append (Scanner.nextline ());
				}
				Scanner.close ();
			}
		Zip.close ();
		
		return content.tostring ();
	}




Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.