The previous article explained how to generate an excel file. In this chapter, let's talk about how to package multiple excel files into a compressed package.
First look at the main function:
public static void main(String[] args) throws IOException { try { File file1 = new File("students1.xls"); File file2 = new File("students2.xls"); File file3 = new File("students3.xls"); //Create three files and put them in the list ArrayList list = new ArrayList(); list.add(file1); list.add(file2); list.add(file3); //Create a temporary archive File file = new File("e:/certpics.rar"); //create file input and output stream FileOutputStream fous = new FileOutputStream(file); /** For the packaging method, we will use an output stream such as ZipOutputStream*/ ZipOutputStream zipOut= new ZipOutputStream(fous); //Enter the packaging method zipFile(list, zipOut); zipOut.close(); fous.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace (); } }
The main function contains a zipFile() method, which will be shown to you next:
/** * Pack all accepted files into a compressed package */ @SuppressWarnings("rawtypes") public static void zipFile(List files,ZipOutputStream outputStream) { int size = files.size(); for(int i = 0; i < size; i++) { File file = (File) files.get(i); zipFile(file, outputStream); } }There is a zipFile() function in the above function. Note that this is the parameter of the method, but it is different.
/** * Pack the file according to the input file and output stream * @param File * @param org.apache.tools.zip.ZipOutputStream */ public static void zipFile(File inputFile,ZipOutputStream ouputStream) { System.out.println(inputFile.getName()); try { ZipEntry entry1 = new ZipEntry(inputFile.getName()); ouputStream.putNextEntry(entry1); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }After running, you can go to your e drive to find the compressed package called certpics.rar.