Java Convert via ByteBuffer toString(InputStream is)

Here you can find the source of toString(InputStream is)

Description

to String

License

Open Source License

Declaration

public static String toString(InputStream is) throws IOException 

Method Source Code


//package com.java2s;
/*//from   w  ww  .  ja  v a  2  s . c o  m
 * Copyright (c) 2014 Magnet Systems, Inc.
 * All rights reserved.
 *
 * 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.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

public class Main {
    public static String toString(InputStream is) throws IOException {
        StringBuilder result = new StringBuilder();
        InputStreamReader in = new InputStreamReader(is);
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        int nRead;
        byte[] data = new byte[16384];

        while ((nRead = is.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }

        buffer.flush();

        return new String(buffer.toByteArray(), Charset.forName("UTF-8"));
    }

    public static byte[] toByteArray(InputStream inputStream) throws IOException {
        // this dynamically extends to take the bytes you read
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();

        // this is storage overwritten on each iteration with bytes
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        // we need to know how may bytes were read to write them to the
        // byteBuffer
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }

        // and then we can return your byte array.
        return byteBuffer.toByteArray();
    }
}

Related

  1. toSimpleList(List attrValues)
  2. toString(byte[] buf, int arrayOffset, int origLimit, StringBuilder sb)
  3. toString(byte[] value, int offset, int length, String encoding)
  4. toString(final String filename)
  5. toString(final Xid xid)
  6. toString(Object o)
  7. toString(Reader r)
  8. toString(Reader reader)
  9. toText(@Nonnull byte[] bytes)