1 /* 2 * Copyright 2018 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.pump.util; 18 19 import androidx.annotation.NonNull; 20 import androidx.annotation.Nullable; 21 import androidx.annotation.WorkerThread; 22 23 import java.io.ByteArrayOutputStream; 24 import java.io.Closeable; 25 import java.io.File; 26 import java.io.FileInputStream; 27 import java.io.IOException; 28 import java.io.InputStream; 29 import java.io.OutputStream; 30 31 @WorkerThread 32 public final class IoUtils { 33 private static final String TAG = Clog.tag(IoUtils.class); 34 IoUtils()35 private IoUtils() { } 36 readFromFile(@onNull File file)37 public static @NonNull byte[] readFromFile(@NonNull File file) throws IOException { 38 InputStream inputStream = new FileInputStream(file); 39 try { 40 return readFromStream(inputStream); 41 } finally { 42 close(inputStream); 43 } 44 } 45 readFromStream(@onNull InputStream inputStream)46 public static @NonNull byte[] readFromStream(@NonNull InputStream inputStream) 47 throws IOException { 48 ByteArrayOutputStream buffer = new ByteArrayOutputStream(); 49 try { 50 int num; 51 byte[] buf = new byte[16384]; 52 while ((num = inputStream.read(buf, 0, buf.length)) >= 0) { 53 buffer.write(buf, 0, num); 54 } 55 return buffer.toByteArray(); 56 } finally { 57 close(buffer); 58 } 59 } 60 writeToStream(@onNull OutputStream outputStream, @NonNull byte[] buffer)61 public static void writeToStream(@NonNull OutputStream outputStream, @NonNull byte[] buffer) 62 throws IOException { 63 outputStream.write(buffer); 64 outputStream.flush(); 65 } 66 close(@ullable Closeable closeable)67 public static void close(@Nullable Closeable closeable) { 68 if (closeable == null) return; 69 try { 70 closeable.close(); 71 } catch (IOException e) { 72 Clog.w(TAG, "Failed to close '" + closeable + "'", e); 73 } 74 } 75 } 76