Java ByteArrayOutputStream Write readAllFrom(InputStream in, boolean chunked)

Here you can find the source of readAllFrom(InputStream in, boolean chunked)

Description

read All From

License

Apache License

Declaration

public static byte[] readAllFrom(InputStream in, boolean chunked) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.*;

public class Main {
    public static final String ENCODING = "UTF-8";

    public static byte[] readAllFrom(InputStream in, boolean chunked) {
        if (in == null)
            throw new RuntimeException("Stream can't be null");
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {/*  ww w  .  ja  v  a 2  s .co  m*/
            byte[] buf = new byte[1024];
            int len;
            len = in.read(buf);
            //System.out.println("READ: " + len + "bytes for the first time");
            while (len > 0) {

                bos.write(buf, 0, len);
                if (chunked) {
                    byte[] check = new String(bos.toByteArray(), ENCODING)
                            .trim().getBytes(ENCODING);

                    if (check.length >= 1) {

                        if (check[check.length - 1] == '0') {
                            if (check.length == 1)
                                break;
                            if ((check[check.length - 2]) == '\n') {
                                break;
                            }

                        }

                    }
                }

                len = in.read(buf);

            }
        } catch (Exception e) {
            throw new RuntimeException("Unable to read:", e);
        } finally {
            try {
                bos.close();
            } catch (Exception io) {
                io.printStackTrace();
            }

        }
        return bos.toByteArray();

    }
}

Related

  1. readAll(InputStream s)
  2. readAll(InputStream stream)
  3. readAllAndClose(InputStream is)
  4. readAllAndKeepOpen(InputStream bytes, int bufferSize)
  5. readAllBinary(InputStream stream)
  6. readAllFromFile(File f)
  7. readAllFromFile(String file)
  8. readAllTextFromResource(String resourceName)