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 java.io.ByteArrayOutputStream; 20 import java.io.File; 21 import java.io.FileInputStream; 22 import java.io.IOException; 23 import java.io.InputStream; 24 import java.io.OutputStream; 25 26 /** 27 * Supports various IO utility functions 28 */ 29 public class IOUtils { 30 31 private static final int BUF_SIZE = 0x1000; // 4K 32 toByteArray(File file)33 public static byte[] toByteArray(File file) throws IOException { 34 try (InputStream in = new FileInputStream(file)) { 35 return toByteArray(in); 36 } 37 } 38 toByteArray(InputStream in)39 public static byte[] toByteArray(InputStream in) throws IOException { 40 ByteArrayOutputStream out = new ByteArrayOutputStream(); 41 copy(in, out); 42 return out.toByteArray(); 43 } 44 copy(InputStream from, OutputStream to)45 public static long copy(InputStream from, OutputStream to) throws IOException { 46 byte[] buf = new byte[BUF_SIZE]; 47 long total = 0; 48 int r; 49 while ((r = from.read(buf)) != -1) { 50 to.write(buf, 0, r); 51 total += r; 52 } 53 return total; 54 } 55 } 56