2 * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.onap.vfc.nfvo.emsdriver.commons.utils;
19 import java.io.FileInputStream;
20 import java.io.FileOutputStream;
21 import java.io.IOException;
22 import java.util.zip.ZipEntry;
23 import java.util.zip.ZipOutputStream;
27 protected int compressDirectoryCount = 0;
28 protected int compressFileCount = 0;
29 protected int relativeAddrIdx = 0;
30 protected int compressLevel = 6;
31 protected String zipFilePath = null;
32 protected String compressPath = null;
33 protected ZipOutputStream zipOutput = null;
35 public Zip(String compressPath, String zipFilePath) throws IOException {
36 File compressFile = new File(compressPath);
37 if (!compressFile.exists())
38 throw new IOException("the file or directory '" + compressPath + "' not found!");
39 this.zipFilePath = zipFilePath;
40 this.compressPath = compressFile.getAbsolutePath();
42 relativeAddrIdx = this.compressPath.lastIndexOf(File.separator) + 1;
45 public void compress() throws IOException {
46 File theFile = new File(zipFilePath);
47 if (!theFile.exists()) {
48 String parentPath = theFile.getParent();
49 if (parentPath != null)
50 new File(parentPath).mkdirs();
51 theFile.createNewFile();
53 zipOutput = new ZipOutputStream(new FileOutputStream(zipFilePath));
54 zipOutput.setMethod(ZipOutputStream.DEFLATED);
55 zipOutput.setLevel(compressLevel);
56 compressDirectory(new File(compressPath));
60 protected void compressDirectory(File directoryPath) throws IOException {
61 if (directoryPath.isFile()) {
62 compressFile(directoryPath.getAbsolutePath());
64 File[] listFiles = directoryPath.listFiles();
65 for (int i = 0; i < listFiles.length; i++)
66 if (listFiles[i].isFile()) {
67 compressFile(listFiles[i].getAbsolutePath());
69 compressDirectoryCount++;
70 compressDirectory(listFiles[i]);
75 protected void compressFile(String absolutePath) throws IOException {
77 byte[] byteBuf = new byte[2048];
78 zipOutput.putNextEntry(new ZipEntry(absolutePath.substring(relativeAddrIdx)));
80 try( FileInputStream input = new FileInputStream(absolutePath)){
81 for (int count = 0; (count = input.read(byteBuf, 0, byteBuf.length)) != -1; )
82 zipOutput.write(byteBuf, 0, count);
84 zipOutput.closeEntry();
88 public void setCompressLevel(int level) {
89 compressLevel = level;