How to load a File into Byte Array in Java ?

Below java code shows how to load a file into Byte Array and print the Byte Array –

 

/****************************************************************************************
 * Created on 03-2012 Copyright(c) http://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.javaio;

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

/**
 * Created by http://kodehelp.com
 * Date: 03/05/2012
 */
public class LoadFileToByteArray {

	public static void main(String[] args) {
		byte readBuf[] = new byte[512*1024];
	    try {
	      FileInputStream fin = new FileInputStream(new File("/sample.log"));
	      ByteArrayOutputStream bout = new ByteArrayOutputStream();

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

	      fin.close();

	      byte byteArray[] = bout.toByteArray();
	      for(int i=0; i<byteArray.length;i++){
	    	  System.out.print((char)byteArray[i]);
	      }

	    }
	    catch (Exception e) {
	      e.printStackTrace();
	    }

	}

}

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.