Java: da un InputStream ad un array di byte

Questa semplice funzione prende in ingresso un InputStream e restituisce un array di byte.

public static byte[] readBytes(InputStream inputStream) throws IOException {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		try {
			byte[] b = new byte[1024];
			int len = 0;
			while ((len = inputStream.read(b, 0, b.length)) != -1) {
				outputStream.write(b, 0, len);
			}
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (Throwable t) {
				}
			}
			try {
				outputStream.close();
			} catch (Throwable t) {
			}
		}
		return outputStream.toByteArray();
	}

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>