Java BufferedInputStream Create getStream(String string)

Here you can find the source of getStream(String string)

Description

Gets a stream for the given string.

License

fedora commons license

Declaration

public static InputStream getStream(String string) 

Method Source Code


//package com.java2s;
/*/*  w w  w.j  a  v  a2s .c  o m*/
 * This is a slightly modified version of the org.fcrepo.server.utilities.StreamUtility file.
 *
 * The original license was as follow:
 *      The contents of this file are subject to the license and copyright terms
 *      detailed in the license directory at the root of the source tree (also
 *      available online at http://fedora-commons.org/license/).
 *
 */

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

public class Main {
    /**
     * Gets a stream for the given string.
     */
    public static InputStream getStream(String string) {
        try {
            return new ByteArrayInputStream(string.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException wontHappen) {
            throw new RuntimeException(wontHappen);
        }
    }

    /**
     * Gets a byte array for the given input stream.
     */
    public static byte[] getBytes(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        pipeStream(in, out, 4096);
        return out.toByteArray();
    }

    /**
     * Copies the contents of an InputStream to an OutputStream, then closes
     * both.
     *
     * @param in
     *        The source stream.
     * @param out
     *        The target stram.
     * @param bufSize
     *        Number of bytes to attempt to copy at a time.
     * @throws IOException
     *         If any sort of read/write error occurs on either stream.
     */
    public static void pipeStream(InputStream in, OutputStream out, int bufSize) throws IOException {
        try {
            byte[] buf = new byte[bufSize];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            try {
                in.close();
                out.close();
            } catch (IOException e) {
                System.err.println("Unable to close stream.");
                e.printStackTrace();
            }
        }
    }
}

Related

  1. getStream(final File file)
  2. getStream(final String string, final String codePage)
  3. getStream(InputStream is)
  4. getStream(String name)
  5. getStream(String resource)
  6. getStream(String string, String codePage)
  7. getStreamFromString(String text)
  8. inputStreamBuffered(final File file)
  9. toBufferedInputStream(InputStream inputStream)