Java tutorial
//package com.java2s; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Main { public static byte[] getBytes(InputStream is) throws IOException { ByteArrayOutputStream os = null; try { os = new ByteArrayOutputStream(); copyStream(is, os); } finally { os.close(); } return os.toByteArray(); } public static byte[] getBytes(File file) throws Exception { FileInputStream fis = null; ByteArrayOutputStream baos = null; try { fis = new FileInputStream(file); baos = new ByteArrayOutputStream(); copyStream(fis, baos); return baos.toByteArray(); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { e.printStackTrace(); } } } } public static void copyStream(InputStream is, OutputStream os) throws IOException { byte buffer[] = new byte[1024]; int len = -1; while ((len = is.read(buffer, 0, 1024)) != -1) { os.write(buffer, 0, len); } } }