1 /* 2 * Copyright (C) 2016 The Android Open Source Project 3 * Copyright (C) 2016 Mopria Alliance, Inc. 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 package com.android.bips.util; 18 19 import android.util.Log; 20 21 import java.io.File; 22 import java.io.IOException; 23 import java.io.InputStream; 24 import java.io.OutputStream; 25 26 public class FileUtils { 27 private static final String TAG = FileUtils.class.getSimpleName(); 28 private static final boolean DEBUG = false; 29 30 private static final int BUFFER_SIZE = 8092; 31 32 /** Recursively delete the target (file or directory) and everything beneath it */ deleteAll(File target)33 public static void deleteAll(File target) { 34 if (DEBUG) Log.d(TAG, "Deleting " + target); 35 if (target.isDirectory()) { 36 for (File child : target.listFiles()) { 37 deleteAll(child); 38 } 39 } 40 target.delete(); 41 } 42 43 /** Copy files from source to target, closing each stream when done */ copy(InputStream source, OutputStream target)44 public static void copy(InputStream source, OutputStream target) throws IOException { 45 try (InputStream in = source; OutputStream out = target) { 46 final byte[] buffer = new byte[BUFFER_SIZE]; 47 int count; 48 while ((count = in.read(buffer)) > 0) { 49 if (count > 0) { 50 out.write(buffer, 0, count); 51 } 52 } 53 } 54 } 55 56 /** Return true if a directory exists or was made at the specified location */ makeDirectory(File dir)57 public static boolean makeDirectory(File dir) { 58 if (DEBUG) { 59 Log.d(TAG, "Testing file " + dir + " exists=" + dir.exists() 60 + " isDirectory=" + dir.isDirectory()); 61 } 62 if (dir.exists()) { 63 return dir.isDirectory(); 64 } 65 return dir.mkdir(); 66 } 67 } 68