Thursday, March 5, 2015

Read file to byte array in Java

P
There are many ways to read a file to byte array in Java, now in this post, I just give you to ways.
1/ Use java.io

public static byte[] read(String path) throws IOException {
     File file = new File(path);
     ByteArrayOutputStream ous = null;
     InputStream ios = null;
     try {
         byte[] buffer = new byte[4096];
         ous = new ByteArrayOutputStream();
         ios = new FileInputStream(file);
         int read = 0;
         while ( (read = ios.read(buffer)) != -1 ) {
             ous.write(buffer, 0, read);
         }
     } finally { 
         try {
              if ( ous != null ) 
                  ous.close();
         } catch ( IOException e) {
         }

         try {
              if ( ios != null ) 
                   ios.close();
         } catch ( IOException e) {
         }
     }
     return ous.toByteArray();
 }

2/ Use org.apache.commons.io.IOUtils

public static byte[] read(String path) throws IOException {
   InputStream in = new FileInputStream(path);
   return IOUtils.toByteArray(in);
  }

You can download apache library from here.

No comments:

Post a Comment