1/* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. 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 18package tests.support; 19 20import java.io.ByteArrayOutputStream; 21import java.io.IOException; 22import java.io.InputStream; 23import java.io.Reader; 24import java.io.StringWriter; 25 26/** 27 * Utility methods for working with byte and character streams. 28 */ 29public class Streams { 30 private Streams() {} 31 32 /** 33 * Drains the stream into a byte array and returns the result. 34 */ 35 public static byte[] streamToBytes(InputStream source) throws IOException { 36 byte[] buffer = new byte[1024]; 37 ByteArrayOutputStream out = new ByteArrayOutputStream(); 38 int count; 39 while ((count = source.read(buffer)) != -1) { 40 out.write(buffer, 0, count); 41 } 42 return out.toByteArray(); 43 } 44 45 /** 46 * Drains the stream into a string and returns the result. 47 */ 48 public static String streamToString(Reader fileReader) throws IOException { 49 char[] buffer = new char[1024]; 50 StringWriter out = new StringWriter(); 51 int count; 52 while ((count = fileReader.read(buffer)) != -1) { 53 out.write(buffer, 0, count); 54 } 55 return out.toString(); 56 } 57} 58