1/* 2 * Copyright (C) 2014 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 17package com.android.camera.util; 18 19import java.io.File; 20import java.io.FileInputStream; 21import java.io.IOException; 22 23/** 24 * Common file operations. 25 */ 26public class FileUtil { 27 /** 28 * Deletes the given directory and all it's contents, including 29 * sub-directories. 30 * 31 * @param directory The directory to delete. 32 * @return Whether The deletion was a success. 33 */ 34 public static boolean deleteDirectoryRecursively(File directory) { 35 if (!directory.exists() || !directory.isDirectory()) { 36 return false; 37 } 38 39 for (File entry : directory.listFiles()) { 40 if (entry.isDirectory()) { 41 deleteDirectoryRecursively(entry); 42 } 43 if (!entry.delete()) { 44 return false; 45 } 46 } 47 return directory.delete(); 48 } 49 50 /** 51 * Reads the content of a {@code File} as a byte array. 52 * 53 * @param file The file to read 54 * @return The content of the file 55 * @throws java.io.IOException if the content of the {@code File} could not be read 56 */ 57 public static byte[] readFileToByteArray(File file) throws IOException { 58 int length = (int) file.length(); 59 byte[] data = new byte[length]; 60 FileInputStream stream = new FileInputStream(file); 61 try { 62 int offset = 0; 63 while (offset < length) { 64 offset += stream.read(data, offset, length - offset); 65 } 66 } catch (IOException e) { 67 throw e; 68 } finally { 69 stream.close(); 70 } 71 return data; 72 } 73 74} 75