Konwertuj strumień wejściowy na tablicę bajtów w Javie

Jak odczytać całą InputStream do tablicy bajtów?

Author: Duncan Jones, 2009-08-12

30 answers

Możesz użyć ApacheCommons IO do obsługi tego i podobnych zadań.

Typ IOUtils ma statyczną metodę odczytu InputStream i zwracania byte[].

InputStream is;
byte[] bytes = IOUtils.toByteArray(is);

Wewnętrznie tworzy ByteArrayOutputStream i kopiuje bajty na wyjście, a następnie wywołuje toByteArray(). Obsługuje duże pliki kopiując bajty w blokach 4kib.

 960
Author: Rich Seller,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-11 17:33:29

Musisz odczytać każdy bajt z InputStream i zapisać go do ByteArrayOutputStream. Następnie można pobrać bazową tablicę bajtów, wywołując toByteArray(); np.

InputStream 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 buffer.toByteArray();
 401
Author: Adamski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-30 13:18:09

Wreszcie, po dwudziestu latach, jest proste rozwiązanie bez potrzeby korzystania z biblioteki stron trzecich, dzięki Java 9:

InputStream is;
…
byte[] array = is.readAllBytes();

Zwróć również uwagę na metody wygodyreadNBytes(byte[] b, int off, int len) oraz transferTo(OutputStream) zaspokajanie powtarzających się potrzeb.

 192
Author: Holger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-18 06:26:12

Jeśli zdarzy ci się użyć Google guava , będzie to tak proste, jak:

byte[] bytes = ByteStreams.toByteArray(inputStream);
 108
Author: bertie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-20 07:17:03

Użyj metody vanilla Java DataInputStream i jej metody readFully (istnieje od co najmniej Javy 1.4):

...
byte[] imgDataBa = new byte[(int)imgFile.length()];
DataInputStream dataIs = new DataInputStream(new FileInputStream(imgFile));
dataIs.readFully(imgDataBa);
...

Istnieją inne smaki tej metody, ale używam tego cały czas w tym przypadku użycia.

 103
Author: dermoritz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-29 00:40:36
public static byte[] getBytesFromInputStream(InputStream is) throws IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream(); 
    byte[] buffer = new byte[0xFFFF];
    for (int len = is.read(buffer); len != -1; len = is.read(buffer)) { 
        os.write(buffer, 0, len);
    }
    return os.toByteArray();
}
 34
Author: oliverkn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-28 10:21:35

Jak zawsze, również Spring framework (spring-core od wersji 3.2.2) ma coś dla ciebie: StreamUtils.copyToByteArray()

 24
Author: Arne Burmeister,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-18 13:59:53

Czy naprawdę potrzebujesz obrazu jako byte[]? Czego dokładnie oczekujesz w byte[] - pełnej zawartości pliku obrazu, zakodowanej w dowolnym formacie pliku obrazu, lub wartości pikseli RGB?

Inne odpowiedzi tutaj pokazują, jak odczytać plik do byte[]. Twój byte[] będzie zawierał dokładną zawartość pliku, i musisz go dekodować, aby zrobić cokolwiek z danymi obrazu.

Standardowym API Javy do odczytu (i zapisu) obrazów jest ImageIO API, które można Znajdź w opakowaniu javax.imageio. Można odczytać obraz z pliku zawierającego tylko jedną linię kodu:

BufferedImage image = ImageIO.read(new File("image.jpg"));

To da ci BufferedImage, a nie byte[]. Aby uzyskać dane obrazu, możesz zadzwonić getRaster() na BufferedImage. To daje Raster obiekt, który ma metody dostępu do danych pikseli (ma kilka getPixel() / getPixels() metody).

Przeszukuje dokumentację API dla javax.imageio.ImageIO, java.awt.image.BufferedImage, java.awt.image.Raster itd.

ImageIO domyślnie obsługuje wiele formatów obrazów: JPEG, PNG, BMP, WBMP i GIF. Możliwe jest dodanie obsługi większej liczby formatów (potrzebna będzie wtyczka implementująca interfejs dostawcy usług ImageIO).

Zobacz także poniższy samouczek: praca z obrazkami

 20
Author: Jesper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-05 13:42:50

Jeśli nie chcesz korzystać z biblioteki Apache commons-io, ten fragment jest pobrany ze słońca.misc.Zajęcia joutils. Jest prawie dwa razy szybsza od zwykłej implementacji wykorzystującej Bytebuffery:

public static byte[] readFully(InputStream is, int length, boolean readAll)
        throws IOException {
    byte[] output = {};
    if (length == -1) length = Integer.MAX_VALUE;
    int pos = 0;
    while (pos < length) {
        int bytesToRead;
        if (pos >= output.length) { // Only expand when there's no room
            bytesToRead = Math.min(length - pos, output.length + 1024);
            if (output.length < pos + bytesToRead) {
                output = Arrays.copyOf(output, pos + bytesToRead);
            }
        } else {
            bytesToRead = output.length - pos;
        }
        int cc = is.read(output, pos, bytesToRead);
        if (cc < 0) {
            if (readAll && length != Integer.MAX_VALUE) {
                throw new EOFException("Detect premature EOF");
            } else {
                if (output.length != pos) {
                    output = Arrays.copyOf(output, pos);
                }
                break;
            }
        }
        pos += cc;
    }
    return output;
}
 14
Author: Kristian Kraljic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-17 14:04:14

W przypadku, gdy ktoś nadal szuka rozwiązania bez zależności i Jeśli Masz plik .

1) DataInputStream

 byte[] data = new byte[(int) file.length()];
 DataInputStream dis = new DataInputStream(new FileInputStream(file));
 dis.readFully(data);
 dis.close();

2) ByteArrayOutputStream

 InputStream is = new FileInputStream(file);
 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
 int nRead;
 byte[] data = new byte[(int) file.length()];
 while ((nRead = is.read(data, 0, data.length)) != -1) {
     buffer.write(data, 0, nRead);
 }

3) RandomAccessFile

 RandomAccessFile raf = new RandomAccessFile(file, "r");
 byte[] data = new byte[(int) raf.length()];
 raf.readFully(data);
 10
Author: harsh_v,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-02 16:57:28

@Adamski: można całkowicie uniknąć bufora.

Kod skopiowany z http://www.exampledepot.com/egs/java.io/File2ByteArray.html (tak, jest bardzo gadatliwy, ale potrzebuje o połowę mniej pamięci niż inne rozwiązanie.)

// Returns the contents of the file in a byte array.
public static byte[] getBytesFromFile(File file) throws IOException {
    InputStream is = new FileInputStream(file);

    // Get the size of the file
    long length = file.length();

    // You cannot create an array using a long type.
    // It needs to be an int type.
    // Before converting to an int type, check
    // to ensure that file is not larger than Integer.MAX_VALUE.
    if (length > Integer.MAX_VALUE) {
        // File is too large
    }

    // Create the byte array to hold the data
    byte[] bytes = new byte[(int)length];

    // Read in the bytes
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length
           && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
        offset += numRead;
    }

    // Ensure all the bytes have been read in
    if (offset < bytes.length) {
        throw new IOException("Could not completely read file "+file.getName());
    }

    // Close the input stream and return bytes
    is.close();
    return bytes;
}
 8
Author: pihentagy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-08 08:30:49
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
while (true) {
    int r = in.read(buffer);
    if (r == -1) break;
    out.write(buffer, 0, r);
}

byte[] ret = out.toByteArray();
 8
Author: YulCheney,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-01 02:25:06
Input Stream is ...
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int next = in.read();
while (next > -1) {
    bos.write(next);
    next = in.read();
}
bos.flush();
byte[] result = bos.toByteArray();
bos.close();
 5
Author: Aturio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-19 16:43:15

Java 9 da Ci wreszcie fajną metodę:

InputStream in = ...;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
in.transferTo( bos );
byte[] bytes = bos.toByteArray();
 3
Author: Christian Ullenboom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-28 20:55:23

Wiem, że jest za późno, ale tutaj myślę, że jest czystsze rozwiązanie, które jest bardziej czytelne...

/**
 * method converts {@link InputStream} Object into byte[] array.
 * 
 * @param stream the {@link InputStream} Object.
 * @return the byte[] array representation of received {@link InputStream} Object.
 * @throws IOException if an error occurs.
 */
public static byte[] streamToByteArray(InputStream stream) throws IOException {

    byte[] buffer = new byte[1024];
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    int line = 0;
    // read bytes from stream, and store them in buffer
    while ((line = stream.read(buffer)) != -1) {
        // Writes bytes from byte array (buffer) into output stream.
        os.write(buffer, 0, line);
    }
    stream.close();
    os.flush();
    os.close();
    return os.toByteArray();
}
 2
Author: Simple-Solution,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-03 11:27:16

Próbowałem edytować odpowiedź @ numan z poprawką do zapisu danych śmieci, ale edycja została odrzucona. Chociaż ten krótki fragment kodu nie jest niczym genialnym, nie widzę innej lepszej odpowiedzi. Oto co ma dla mnie największy sens:

ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024]; // you can configure the buffer size
int length;

while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); //copy streams
in.close(); // call this in a finally block

byte[] result = out.toByteArray();

Btw ByteArrayOutputStream nie musi być zamknięty. try / finally konstrukty pominięte dla czytelności

 1
Author: akostadinov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-20 07:22:25

Zobacz InputStream.available() dokumentację:

Jest szczególnie ważne, aby zdać sobie sprawę, że nie wolno używać tego sposób na rozmiar kontenera i założenie, że można odczytać całość strumienia bez konieczności zmiany rozmiaru pojemnika. Tacy rozmówcy powinni chyba napisać wszystko, co przeczytali do ByteArrayOutputStream i przekonwertować ją na tablicę bajtów. Alternatywnie, jeśli czytasz z pliku, Pliku.length zwraca bieżącą długość pliku (choć zakładając, że długość pliku nie może ulec zmianie może być nieprawidłowa, odczyt pliku jest z natury racy).

 1
Author: yichouangle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-18 14:50:20

Java 7 i Później:

import sun.misc.IOUtils;
...
InputStream in = ...;
byte[] buf = IOUtils.readFully(in, -1, false);
 1
Author: Antonio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-20 07:56:04

Java 8 way (dzięki BufferedReader i Adam Bien)

private static byte[] readFully(InputStream input) throws IOException {
    try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) {
        return buffer.lines().collect(Collectors.joining("\n")).getBytes(<charset_can_be_specified>);
    }
}

Zauważ że to rozwiązanie usuwareturn ('\R') i może być nieodpowiednie.

 1
Author: Ilya Bystrov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-03 07:32:21

Drugi przypadek, aby uzyskać poprawną tablicę bajtów poprzez stream, po wysłaniu żądania do serwera i oczekiwaniu na odpowiedź.

/**
         * Begin setup TCP connection to PC app
         * to open integrate connection between mobile app and pc app (or mobile app)
         */
        mSocket = new Socket(IP, port);
       // mSocket.setSoTimeout(30000);

        DataOutputStream mDos = new DataOutputStream(mSocket.getOutputStream());

        String str = "MobileRequest#" + params[0] + "#<EOF>";

        mDos.write(str.getBytes());

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        /* Since data are accepted as byte, all of them will be collected in the
        following byte array which initialised with accepted data length. */
        DataInputStream mDis = new DataInputStream(mSocket.getInputStream());
        byte[] data = new byte[mDis.available()];

        // Collecting data into byte array
        for (int i = 0; i < data.length; i++)
            data[i] = mDis.readByte();

        // Converting collected data in byte array into String.
        String RESPONSE = new String(data);
 0
Author: Huy Tower,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-14 08:03:17

Robisz dodatkową kopię, jeśli używasz ByteArrayOutputStream. Jeśli znasz długość strumienia przed rozpoczęciem jego czytania (np. strumień wejściowy jest w rzeczywistości strumieniem plików i możesz wywołać plik.length() na pliku, lub InputStream jest wpisem zipfile InputStream i możesz wywołać zipEntry.length ()), wtedy o wiele lepiej jest zapisywać Bezpośrednio do tablicy byte [] -- zużywa połowę pamięci i oszczędza czas.

// Read the file contents into a byte[] array
byte[] buf = new byte[inputStreamLength];
int bytesRead = Math.max(0, inputStream.read(buf));

// If needed: for safety, truncate the array if the file may somehow get
// truncated during the read operation
byte[] contents = bytesRead == inputStreamLength ? buf
                  : Arrays.copyOf(buf, bytesRead);

N. B. ostatnia linijka powyżej dotyczy plików uzyskiwanych okrojona podczas odczytu strumienia, jeśli trzeba obsłużyć tę możliwość, ale jeśli plik zostanie dłuższy podczas odczytu strumienia, zawartość tablicy bajtu[] nie zostanie wydłużona w celu uwzględnienia nowej zawartości pliku, tablica zostanie po prostu obcięta do starej długości inputStreamLength.

 0
Author: Luke Hutchison,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-30 11:26:43

Używam tego.

public static byte[] toByteArray(InputStream is) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {
            byte[] b = new byte[4096];
            int n = 0;
            while ((n = is.read(b)) != -1) {
                output.write(b, 0, n);
            }
            return output.toByteArray();
        } finally {
            output.close();
        }
    }
 0
Author: cchcc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-13 05:05:40

To jest moja wersja kopiuj-wklej:

@SuppressWarnings("empty-statement")
public static byte[] inputStreamToByte(InputStream is) throws IOException {
    if (is == null) {
        return null;
    }
    // Define a size if you have an idea of it.
    ByteArrayOutputStream r = new ByteArrayOutputStream(2048);
    byte[] read = new byte[512]; // Your buffer size.
    for (int i; -1 != (i = is.read(read)); r.write(read, 0, i));
    is.close();
    return r.toByteArray();
}
 0
Author: Daniel De León,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-11 04:10:14

Owinąć go w DataInputStream jeśli to jest poza tabelą z jakiegoś powodu, po prostu użyj read, aby młotkować go, dopóki nie da ci -1 lub cały blok, o który prosiłeś.

public int readFully(InputStream in, byte[] data) throws IOException {
    int offset = 0;
    int bytesRead;
    boolean read = false;
    while ((bytesRead = in.read(data, offset, data.length - offset)) != -1) {
        read = true;
        offset += bytesRead;
        if (offset >= data.length) {
            break;
        }
    }
    return (read) ? offset : -1;
}
 0
Author: Tatarize,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-03 08:22:24

Możesz spróbować Cactoos :

byte[] array = new BytesOf(stream).bytes();
 0
Author: yegor256,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-27 12:58:40

Widzimy pewne opóźnienie dla kilku transakcji AWS podczas konwersji obiektu S3 na ByteArray.

Uwaga: obiekt S3 to dokument PDF (maksymalny rozmiar to 3 mb).

Używamy opcji # 1 (org.apache.commons.io.ioutils), aby przekonwertować obiekt S3 na ByteArray. Zauważyliśmy, że S3 dostarcza wbudowaną metodę IOUtils do konwersji obiektu S3 na ByteArray, prosimy o potwierdzenie, jaki jest najlepszy sposób konwersji obiektu S3 na ByteArray, aby uniknąć opóźnienia.

Opcja #1:

import org.apache.commons.io.IOUtils;
is = s3object.getObjectContent();
content =IOUtils.toByteArray(is);

Opcja # 2:

import com.amazonaws.util.IOUtils;
is = s3object.getObjectContent();
content =IOUtils.toByteArray(is);

Daj mi również znać, jeśli mamy inny lepszy sposób na przekonwertowanie obiektu s3 na bytearray

 0
Author: Bharathiraja S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-04 12:38:37

Oto zoptymalizowana wersja, która stara się unikać kopiowania bajtów danych w jak największym stopniu:

private static byte[] loadStream (InputStream stream) throws IOException {
   int available = stream.available();
   int expectedSize = available > 0 ? available : -1;
   return loadStream(stream, expectedSize);
}

private static byte[] loadStream (InputStream stream, int expectedSize) throws IOException {
   int basicBufferSize = 0x4000;
   int initialBufferSize = (expectedSize >= 0) ? expectedSize : basicBufferSize;
   byte[] buf = new byte[initialBufferSize];
   int pos = 0;
   while (true) {
      if (pos == buf.length) {
         int readAhead = -1;
         if (pos == expectedSize) {
            readAhead = stream.read();       // test whether EOF is at expectedSize
            if (readAhead == -1) {
               return buf;
            }
         }
         int newBufferSize = Math.max(2 * buf.length, basicBufferSize);
         buf = Arrays.copyOf(buf, newBufferSize);
         if (readAhead != -1) {
            buf[pos++] = (byte)readAhead;
         }
      }
      int len = stream.read(buf, pos, buf.length - pos);
      if (len < 0) {
         return Arrays.copyOf(buf, pos);
      }
      pos += len;
   }
}
 0
Author: Christian d'Heureuse,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-27 00:44:32

Poniżej Kody

public static byte[] serializeObj(Object obj) throws IOException {
  ByteArrayOutputStream baOStream = new ByteArrayOutputStream();
  ObjectOutputStream objOStream = new ObjectOutputStream(baOStream);

  objOStream.writeObject(obj); 
  objOStream.flush();
  objOStream.close();
  return baOStream.toByteArray(); 
} 

Lub

BufferedImage img = ...
ByteArrayOutputStream baos = new ByteArrayOutputStream(1000);
ImageIO.write(img, "jpeg", baos);
baos.flush();
byte[] result = baos.toByteArray();
baos.close();
 -1
Author: firstthumb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-08-12 07:38:28
/*InputStream class_InputStream = null;
I am reading class from DB 
class_InputStream = rs.getBinaryStream(1);
Your Input stream could be from any source
*/
int thisLine;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((thisLine = class_InputStream.read()) != -1) {
    bos.write(thisLine);
}
bos.flush();
byte [] yourBytes = bos.toByteArray();

/*Don't forget in the finally block to close ByteArrayOutputStream & InputStream
 In my case the IS is from resultset so just closing the rs will do it*/

if (bos != null){
    bos.close();
}
 -1
Author: Madhu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-02 12:45:02

To działa dla mnie,

if(inputStream != null){
                ByteArrayOutputStream contentStream = readSourceContent(inputStream);
                String stringContent = contentStream.toString();
                byte[] byteArr = encodeString(stringContent);
            }

ReadSourceContent ()

public static ByteArrayOutputStream readSourceContent(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int nextChar;
        try {
            while ((nextChar = inputStream.read()) != -1) {
                outputStream.write(nextChar);
            }
            outputStream.flush();
        } catch (IOException e) {
            throw new IOException("Exception occurred while reading content", e);
        }

        return outputStream;
    }

EncodeString ()

public static byte[] encodeString(String content) throws UnsupportedEncodingException {
        byte[] bytes;
        try {
            bytes = content.getBytes();

        } catch (UnsupportedEncodingException e) {
            String msg = ENCODING + " is unsupported encoding type";
            log.error(msg,e);
            throw new UnsupportedEncodingException(msg, e);
        }
        return bytes;
    }
 -1
Author: tk_,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-26 09:56:54