1 /* 2 * Copyright (C) 2017 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 com.android.launcher3.util; 18 19 import android.os.FileUtils; 20 import android.util.Log; 21 22 import com.android.launcher3.Utilities; 23 import com.android.launcher3.config.FeatureFlags; 24 25 import java.io.ByteArrayOutputStream; 26 import java.io.Closeable; 27 import java.io.File; 28 import java.io.FileInputStream; 29 import java.io.IOException; 30 import java.io.InputStream; 31 import java.io.OutputStream; 32 33 /** 34 * Supports various IO utility functions 35 */ 36 public class IOUtils { 37 38 private static final int BUF_SIZE = 0x1000; // 4K 39 private static final String TAG = "IOUtils"; 40 toByteArray(File file)41 public static byte[] toByteArray(File file) throws IOException { 42 try (InputStream in = new FileInputStream(file)) { 43 return toByteArray(in); 44 } 45 } 46 toByteArray(InputStream in)47 public static byte[] toByteArray(InputStream in) throws IOException { 48 ByteArrayOutputStream out = new ByteArrayOutputStream(); 49 copy(in, out); 50 return out.toByteArray(); 51 } 52 copy(InputStream from, OutputStream to)53 public static long copy(InputStream from, OutputStream to) throws IOException { 54 if (Utilities.ATLEAST_Q) { 55 return FileUtils.copy(from, to); 56 } 57 byte[] buf = new byte[BUF_SIZE]; 58 long total = 0; 59 int r; 60 while ((r = from.read(buf)) != -1) { 61 to.write(buf, 0, r); 62 total += r; 63 } 64 return total; 65 } 66 closeSilently(Closeable c)67 public static void closeSilently(Closeable c) { 68 if (c != null) { 69 try { 70 c.close(); 71 } catch (IOException e) { 72 if (FeatureFlags.IS_STUDIO_BUILD) { 73 Log.d(TAG, "Error closing", e); 74 } 75 } 76 } 77 } 78 } 79