1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 
17 package android.theme.app;
18 
19 import java.io.File;
20 import java.io.FileInputStream;
21 import java.io.FileOutputStream;
22 import java.io.IOException;
23 import java.util.zip.ZipEntry;
24 import java.util.zip.ZipOutputStream;
25 
26 public class ThemeTestUtils {
27 
28     /**
29      * Compresses the contents of a directory to a ZIP file.
30      *
31      * @param dir the directory to compress
32      * @return {@code true} on success, {@code false} on failure
33      */
compressDirectory(File dir, File file)34     public static boolean compressDirectory(File dir, File file) throws IOException {
35         if (dir == null || !dir.exists() || file == null || file.exists()) {
36             return false;
37         }
38 
39         final File[] srcFiles = dir.listFiles();
40         if (srcFiles.length == 0) {
41             return false;
42         }
43 
44         final ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(file));
45         final byte[] data = new byte[4096];
46         for (int i = 0; i < srcFiles.length; i++) {
47             final FileInputStream fileIn = new FileInputStream(srcFiles[i]);
48             final ZipEntry entry = new ZipEntry(srcFiles[i].getName());
49             zipOut.putNextEntry(entry);
50 
51             int count;
52             while ((count = fileIn.read(data, 0, data.length)) != -1) {
53                 zipOut.write(data, 0, count);
54                 zipOut.flush();
55             }
56 
57             zipOut.closeEntry();
58             fileIn.close();
59         }
60 
61         zipOut.close();
62         return true;
63     }
64 
65     /**
66      * Recursively deletes a directory and its contents.
67      *
68      * @param dir the directory to delete
69      * @return {@code true} on success, {@code false} on failure
70      */
deleteDirectory(File dir)71     public static boolean deleteDirectory(File dir) {
72         final File files[] = dir.listFiles();
73         if (files != null) {
74             for (File file : files) {
75                 deleteDirectory(file);
76             }
77         }
78         return dir.delete();
79     }
80 }
81