Java File read to byte array

Description

Java File read to byte array

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;


public final class Main {
   public static void main(String[] argv){
      byte[] byteArray = load("Main.java");
      System.out.println(Arrays.toString(byteArray));


   }/*w  w  w . j av a 2  s. c  om*/
   public final static byte[] load(String fileName) {
      try {
         FileInputStream fin = new FileInputStream(fileName);
         return load(fin);
      } catch (Exception e) {

         return new byte[0];
      }
   }

   public final static byte[] load(File file) {
      try {
         FileInputStream fin = new FileInputStream(file);
         return load(fin);
      } catch (Exception e) {

         return new byte[0];
      }
   }

   public final static byte[] load(FileInputStream fin) {
      byte readBuf[] = new byte[512 * 1024];

      try {
         ByteArrayOutputStream bout = new ByteArrayOutputStream();

         int readCnt = fin.read(readBuf);
         while (0 < readCnt) {
            bout.write(readBuf, 0, readCnt);
            readCnt = fin.read(readBuf);
         }

         fin.close();

         return bout.toByteArray();
      } catch (Exception e) {

         return new byte[0];
      }
   }

}



PreviousNext

Related