Java Native File packaging

Source: Internet
Author: User

I. BACKGROUND

Front-end time, self-made projects need to pack features, do not want to draw outside the jar package

And then did the function with Java.util.zip.

Second, the application scenario

Generate multiple files, such as Word, Excel, XML, and request package download scenarios

Example: Multi-select export of project information word

Third, the realization

The implementation is divided into three parts, namely

1, save the string as a file, is the most basic IO operation

    /*** @Description Save the string as a file *@authorliuy-8 * @date May 20, 2015 PM 1:48:18 *@paramFilePath *@paramcontent*/     Public Static voidsaveFile (String filePath, string content) {File file=NewFile (FilePath); FileWriter FW=NULL; //Bufferwrite is not used here because the data is write-once//The advantage of Bufferwrite is that the buffer is used when calling the Write method//and FileWriter calls the Write method of Streamencoder each time the Write method is called        Try{FW=NewFileWriter (file);//Buffer 1024 charactersfw.write (content);        Fw.flush (); } Catch(IOException e) {e.printstacktrace (); } finally{            //Close FileWriter            Try {                if(NULL!=FW) Fw.close (); } Catch(IOException e) {e.printstacktrace (); }                    }    }

2, scan all files under the specified folder, prepare the write work of the compressed package

This part is still the basic IO operation, be careful to safely turn off the input and output stream, open and close the order

    /*** @Description Get all the file paths in the folder *@authorliuy-8 * @date May 27, 2015 PM 5:25:24 *@paramFolderPath Folder path *@returnall file paths in the folder*/     Public StaticList<string>Getfilespath (String folderpath) {List<String> Filespath =NewArraylist<string>(); File folder=NewFile (FolderPath); File[] FileList=Folder.listfiles ();  for(File file:filelist) {if(File.isdirectory ()) {//is a folder, recursive traversalFilespath.addall (Getfilespath (File.getpath ())); }Else{                //is file, join file listFilespath.add (File.getpath ()); }        }        returnFilespath; }    /*** @Description Compressed folder *@authorliuy-8 * @date May 26, 2015 PM 1:42:00 *@paramFolderPath Folder path *@paramZipfilepath Compressed file path*/     Public Static voidfolder2zip (String folderpath, String zipfilepath) {//gets the current system file delimiterString fileseparator = System.getproperty ("File.separator"); //If there is no file delimiter at the end of the incoming path, add        if(Folderpath.lastindexof (fileseparator)! = (Folderpath.length ()-1) ) {FolderPath= FolderPath +Fileseparator; }        //get all file paths under folderList<string> Filespath =Getfilespath (FolderPath); //file output streamFileOutputStream fos =NULL; //Buffered output streamBufferedoutputstream BOS =NULL; //Zip output streamZipoutputstream Zos =NULL; Try{fos=NewFileOutputStream (Zipfilepath); Bos=NewBufferedoutputstream (FOS); Zos=NewZipoutputstream (BOS);  for(String filepath:filespath) {//writes a file to the zip output streamWritefile2zip (FolderPath, FilePath, Zos);        } zos.flush (); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } finally{            //close the zip output stream            Try {                if(NULL!=Zos)                {Zos.close (); }            } Catch(IOException e) {e.printstacktrace (); }            //Close buffered output stream            Try {                if(NULL!=Bos)                {Bos.close (); }            } Catch(IOException e) {e.printstacktrace (); }            //close the file output stream            Try {                if(NULL!=Fos)                {Fos.close (); }            } Catch(IOException e) {e.printstacktrace (); }        }    }

3. Write the file to the zip output stream sequentially

In the second step, the output stream of the compressed file has been created with Zipoutputstream, and in this step, each file corresponds to a ZipEntry object

To add this object to the output stream of the compressed file before writing the data, and write the data must close the ZipEntry object in the output stream

Here are 2 error-prone areas:

One is the ZipEntry object needs a path, which is relative to the compressed folder relative path, to ensure that the sub-folder file is successfully pressed into

Second, when the bytes written to the zip output stream, to determine how many bytes read in the file input stream when the bytes are being read, or how much to write, or the wrong data will appear at the end of the file

    /*** @Description write files to the zip output stream *@authorliuy-8 * @date May 27, 2015 PM 5:23:42 *@paramFolderPath folder path to be compressed *@paramFilePath file to be written *@paramzos Zip output stream*/    Private Static voidwritefile2zip (String folderpath, String filePath, Zipoutputstream zos) {//buffers        byte[] bs =New byte[1024]; //gets the relative path of the fileString entryName = filepath.substring (Filepath.indexof (folderpath) +folderpath.length ()); //Create a Zip entityZipEntry entry =NewZipEntry (entryName); //input StreamFileInputStream FIS =NULL; //Buffered input streamBufferedinputstream bis =NULL; Try {            //adding a zip entity to the zip output streamzos.putnextentry (entry); FIS=NewFileInputStream (FilePath); Bis=NewBufferedinputstream (FIS); //write to the zip output stream            intLen = 0;  while(len = bis.read (BS, 0, 1024x768)) > 0) {zos.write (BS,0, Len);        } zos.flush (); } Catch(IOException e) {e.printstacktrace (); } finally{            //Close Entity            Try{zos.closeentry (); } Catch(IOException e) {e.printstacktrace (); }            //Close Bufferedinputstream            Try {                if(NULL!=bis)                {Bis.close (); }            } Catch(IOException e) {e.printstacktrace (); }            //Close FileInputStream            Try {                if(NULL!=FIS)                {Bis.close (); }            } Catch(IOException e) {e.printstacktrace (); }        }    }

This class has been encapsulated as glodonfileutil, there is a need to find me to

Java Native File packaging

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.