Java InputStream Create asInputStream(Object content)

Here you can find the source of asInputStream(Object content)

Description

Returns an input stream for the specified content.

License

Apache License

Parameter

Parameter Description
content The content.

Exception

Parameter Description

Return

an input stream of the content.

Declaration

public static InputStream asInputStream(Object content) throws IOException 

Method Source Code


//package com.java2s;
/*// w ww .  ja v a2 s .c  o m
 * Copyright 2009-2011 Stephen Connolly
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.ByteArrayInputStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class Main {
    /**
     * Returns an input stream for the specified content.  If the content is a byte array, the input stream will be a
     * {@link java.io.ByteArrayInputStream} if the content is a File, the input stream will be a
     * {@link java.io.FileInputStream} otherwise the content will be converted to a String and then into its UTF-8
     * representation and a {@link java.io.ByteArrayInputStream} returned.
     *
     * @param content The content.
     * @return an input stream of the content.
     * @throws java.io.IOException if things go wrong.
     * @since 1.0
     */
    public static InputStream asInputStream(Object content) throws IOException {
        if (content instanceof byte[]) {
            return new ByteArrayInputStream((byte[]) content);
        } else if (content instanceof File) {
            return new FileInputStream((File) content);
        } else {
            return new ByteArrayInputStream(content.toString().getBytes("UTF-8"));
        }
    }
}

Related

  1. asInputStream(byte[] bytes)
  2. asInputStream(File file)
  3. asInputStream(String str)
  4. getInputStream(File f)
  5. getInputStream(File jarFile, String fileName)
  6. getInputStream(File tarFile)