001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019 020package org.apache.isis.core.commons.lang; 021 022import java.io.ByteArrayInputStream; 023import java.io.IOException; 024import java.io.InputStream; 025import java.io.OutputStream; 026import java.io.UnsupportedEncodingException; 027 028public final class InputStreamExtensions { 029 030 private static final int DEFAULT_BUFFER_SIZE = 1024; 031 032 private InputStreamExtensions() { 033 } 034 035 /** 036 * Copy bytes from an <code>InputStream</code> to an 037 * <code>OutputStream</code>. 038 * <p> 039 * This method buffers the input internally, so there is no need to use a 040 * <code>BufferedInputStream</code>. 041 * 042 * @param extendee 043 * the <code>InputStream</code> to read from 044 * @param output 045 * the <code>OutputStream</code> to write to 046 * @return the number of bytes copied 047 * @throws IllegalArgumentException 048 * if the input or output is null 049 * @throws IOException 050 * if an I/O error occurs 051 * @since Commons IO 1.1 052 */ 053 public static int copyTo(final InputStream extendee, final OutputStream output) throws IOException { 054 if (extendee == null) { 055 throw new IllegalArgumentException("InputStream cannot be null"); 056 } 057 if (output == null) { 058 throw new IllegalArgumentException("OutputStream cannot be null"); 059 } 060 final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; 061 int count = 0; 062 int n = 0; 063 while (-1 != (n = extendee.read(buffer))) { 064 output.write(buffer, 0, n); 065 count += n; 066 } 067 return count; 068 } 069 070 public static InputStream asUtf8ByteStream(final String string) throws UnsupportedEncodingException { 071 final byte[] data = string.getBytes("utf-8"); 072 final InputStream in = new ByteArrayInputStream(data); 073 return in; 074 } 075 076}