1 /* 2 * Copyright (C) 2016 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.compatibility.common.util; 18 19 import com.google.common.io.Closeables; 20 21 import java.io.ByteArrayOutputStream; 22 import java.io.IOException; 23 import java.io.InputStream; 24 import java.io.OutputStream; 25 import java.io.Reader; 26 import java.nio.charset.StandardCharsets; 27 28 29 public class StreamUtil { 30 31 // 16K buffer size 32 private static final int BUFFER_SIZE = 16 * 1024; 33 /** 34 * Copies contents of origStream to destStream. 35 * <p/> 36 * Recommended to provide a buffered stream for input and output 37 * 38 * @param inStream the {@link InputStream} 39 * @param outStream the {@link OutputStream} 40 * @throws IOException 41 */ copyStreams(InputStream inStream, OutputStream outStream)42 public static void copyStreams(InputStream inStream, OutputStream outStream) 43 throws IOException { 44 byte[] buf = new byte[BUFFER_SIZE]; 45 int size = -1; 46 while ((size = inStream.read(buf)) != -1) { 47 outStream.write(buf, 0, size); 48 } 49 } 50 51 /** 52 * Reads {@code inputStream} converting it into a string. Does NOT close it. 53 * 54 * @throws IOException 55 */ readInputStream(InputStream inputStream)56 public static String readInputStream(InputStream inputStream) throws IOException { 57 ByteArrayOutputStream result = new ByteArrayOutputStream(); 58 byte[] buffer = new byte[1024]; 59 int length; 60 while ((length = inputStream.read(buffer)) != -1) { 61 result.write(buffer, 0, length); 62 } 63 return result.toString(StandardCharsets.UTF_8.name()); 64 } 65 drainAndClose(Reader reader)66 public static void drainAndClose(Reader reader) { 67 try { 68 while (reader.read() >= 0) {} 69 } catch (IOException ignored) {} 70 Closeables.closeQuietly(reader); 71 } 72 } 73