Encapsulate given content in an InputStream with charset UTF-8. - Java java.io

Java examples for java.io:InputStream Read

Description

Encapsulate given content in an InputStream with charset UTF-8.

Demo Code

//package com.java2s;

import java.io.ByteArrayInputStream;

import java.io.InputStream;

import java.io.UnsupportedEncodingException;

public class Main {
    public static void main(String[] argv) {
        String content = "java2s.com";
        System.out.println(encapsulate(content));
    }//from   w w w.  j av  a  2s. co m

    public static final String DEFAULT_ENCODING = "UTF-8";

    /**
     * Encapsulate given content in an {@link InputStream} with charset <code>UTF-8</code>.
     *
     * @param content to encapsulate content
     * @return content as stream
     */
    public static InputStream encapsulate(final String content) {
        try {
            return encapsulate(content, DEFAULT_ENCODING);
        } catch (UnsupportedEncodingException e) {
            // we know that UTF-8 is supported
            throw new RuntimeException("UTF-8 MUST be supported.", e);
        }
    }

    /**
     * Encapsulate given content in an {@link InputStream} with given charset.
     * 
     * @param content to encapsulate content
     * @param charset to be used charset
     * @return content as stream
     * @throws UnsupportedEncodingException if charset is not supported
     */
    public static InputStream encapsulate(final String content,
            final String charset) throws UnsupportedEncodingException {
        return new ByteArrayInputStream(content.getBytes(charset));
    }
}

Related Tutorials