InputStream to String and Byte array : Byte Array « File Input Output « Java

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JDK 6
25.JNDI LDAP
26.JPA
27.JSP
28.JSTL
29.Language Basics
30.Network Protocol
31.PDF RTF
32.Reflection
33.Regular Expressions
34.Scripting
35.Security
36.Servlets
37.Spring
38.Swing Components
39.Swing JFC
40.SWT JFace Eclipse
41.Threads
42.Tiny Application
43.Velocity
44.Web Services SOA
45.XML
Java » File Input Output » Byte ArrayScreenshots 
InputStream to String and Byte array
 
/*
 * Copyright WizTools.org
 * Licensed under the Apache License, Version 2.0:
 * http://www.apache.org/licenses/LICENSE-2.0
 */
//package org.wiztools.commons;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.MalformedInputException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Common operations on java.io.Stream objects.
 @author subwiz
 */
public final class StreamUtil {

    private static final Logger LOG = Logger.getLogger(StreamUtil.class.getName());

    private StreamUtil(){}

    private static CharBuffer decodeHelper(byte[] byteArray, int numberOfBytes, java.nio.charset.Charset charsetthrows IOException {
        CharsetDecoder decoder = charset.newDecoder();
        CharBuffer charBuffer = null;
        try {
            charBuffer = decoder.decode(ByteBuffer.wrap(byteArray, 0,
                    numberOfBytes));
        catch (MalformedInputException ex) {
            charBuffer = null;
        }
        return charBuffer;


    }

    /**
     * Reads the stream and generates a String content using the charset specified.
     * Stream will be closed at the end of the operation.
     @param in InputStream as the input.
     @param charset The charset to use to create the String object.
     @return The output String.
     @throws IOException
     */
    public static String inputStream2String(final InputStream is,
            final Charset charsetthrows IOException {
        try{
            StringBuilder out = new StringBuilder();
            byte[] b = new byte[4096];
            byte[] savedBytes = new byte[1];
            boolean hasSavedBytes = false;
            CharsetDecoder decoder = charset.newDecoder();
            for (int n; (n = is.read(b)) != -1;) {
                if (hasSavedBytes) {
                    byte[] bTmp = new byte[savedBytes.length + b.length];
                    System.arraycopy(savedBytes, 0, bTmp, 0,
                            savedBytes.length);
                    System.arraycopy(b, 0, bTmp, savedBytes.length, b.length);
                    b = bTmp;
                    hasSavedBytes = false;
                    n = n + savedBytes.length;
                }

                CharBuffer charBuffer = decodeHelper(b, n, charset);
                if (charBuffer == null) {
                    int nrOfChars = 0;
                    while (charBuffer == null) {
                        nrOfChars++;
                        charBuffer = decodeHelper(b, n - nrOfChars, charset);
                        if (nrOfChars > 10 && nrOfChars < n) {
                            try {
                                charBuffer = decoder.decode(ByteBuffer.wrap(b,
                                        0, n));
                            catch (MalformedInputException ex) {
                                throw new IOException(
                                        "File not in supported encoding (" +
                                        charset.displayName() ")", ex);
                            }
                        }
                    }
                    savedBytes = new byte[nrOfChars];
                    hasSavedBytes = true;
                    for (int i = 0; i < nrOfChars; i++) {
                        savedBytes[i= b[n - nrOfChars + i];
                    }
                }

                charBuffer.rewind()// Bring the buffer's pointer to 0
                out.append(charBuffer.toString());
            }
            if (hasSavedBytes) {
                try {
                    CharBuffer charBuffer = decoder.decode(ByteBuffer.wrap(savedBytes, 0, savedBytes.length));
                catch (MalformedInputException ex) {
                    throw new IOException(
                            "File not in supported encoding (" + charset.displayName() ")",
                            ex);
                }
            }
            return out.toString();
        }
        finally{
            if(is != null){
                is.close();
            }
        }
    }

    /**
     * Reads the InputStream and creates a byte[] of the content. The stream
     * will be closed at the end of operation.
     @param is The input InputStream.
     @return The byte[] of the content read.
     @throws IOException
     */
    public static byte[] inputStream2Bytes(final InputStream isthrows IOException{
        try{
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024*8];
            int len = -1;
            while((len = is.read(buf))!=-1){
                baos.write(buf, 0, len);
            }
            return baos.toByteArray()// baos doesn't need close!
        }
        finally{
            is.close();
        }
    }

    /**
     * Copies the content read from InputStream to OutputStream. Uses the NIO Channels to copy.
     @param is The InputStream that is read.
     @param os The OutputStream where the data is written.
     @throws IOException
     */
    public static void copy(final InputStream is, final OutputStream osthrows IOException {
        final ReadableByteChannel inChannel = Channels.newChannel(is);
        final WritableByteChannel outChannel = Channels.newChannel(os);

        try{
            final ByteBuffer buffer = ByteBuffer.allocate(65536);
            while(true) {
                int bytesRead = inChannel.read(buffer);
                if(bytesRead == -1break;
                buffer.flip();
                while(buffer.hasRemaining()) outChannel.write(buffer);
                buffer.clear();
            }
        }
        finally {
            try{inChannel.close();}catch(IOException ex){LOG.log(Level.SEVERE, null, ex);}
            try{outChannel.close();}catch(IOException ex){LOG.log(Level.SEVERE, null, ex);}
        }
    }
}

   
  
Related examples in the same category
1.Load file to byte array
2.Manages fixed-length byte arrays
3.Byte-Array Conversion Utility Functions
4.ByteArray wraps java byte arrays (byte[]) to allow byte arrays to be used as keys in hashtables.
5.Returns a object from the given byte array.
6.Load File as byte array
7.Gets an array of bytes corresponding to the given object
8.An implementation of a virtual file, whose contents are kept in memory
9.Given a hexstring this will return the byte array corresponding to string
10.Decode byte array
11.Compare two byte[] for differences, either may be null
12.Convert the bytes within the specified range of the given byte array into a String
13.Convert the bytes within the specified range of the given byte array into a signed integer
14.Convert the bytes within the specified range of the given byte array into a signed integer in the given radix
15.Convert the bytes within the specified range of the given byte array into a signed long
16.Converts a byte array into a hexadecimal string
17.Converts a byte array into hexadecimal characters which are written as ASCII to the given output stream.
18.Convert byte array into a printable format: a String of hexadecimal digit characters (two per byte).
19.Convert hexadecimal digits into byte array by encoding each two hexadecimal digits as a byte.
20.Get Hex from byte arrayGet Hex from byte array
21.Read file to byte array
22.Invert the endianness of words (4 bytes) in the given byte array starting at the given offset and repeating length/4 times.
23.Returns a hexadecimal representation of the given byte array.
24.Converts a hex string representation to a byte array.
25.extracts floats from byte array
26.Extracts ints from byte array
27.extracts longs from byte array
28.Extracts short ints from byte array
29.writes doubles to byte array
30.writes floats to byte array
31.writes ints to byte array
32.writes longs to byte array
33.writes short ints to byte array
34.Convert a string of hex digits to a byte array, with the first byte in the array being the MSB.
35.Byte Array
36.This class provides encoding of byte arrays into Base64-encoded strings, and decoding the other way.
37.Byte Array for Android
38.Convert byte array to Hex string
39.implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it.
40.Convert a TCP/IP address string into a byte array
41.Read file to byte array and save byte array to file
42.Convert object to byte array and convert byte array to object
43.Byte ArrayList
44.converts an int integer array to a byte array.
45.Compress byte array
46.Utility method to convert byte array to hex-encoded string.
47.Fast Byte Array InputStream
48.Fast Byte Array OutputStream
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.