Sample Programs

Sample java program to read file into byte array


 package org.jusfortechies.example; 

 import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStream;
 
 public class ReadFileIntoByteArray {

   public static void main(String[] args) {
      
      InputStream is = null;
      try {
         File file = new File("C:\\samplefile.txt");

         is = new FileInputStream(file);

         int offset = 0;
         int bytesRead;

         byte[] bytes = new byte[(int) file.length()];

         while (offset < bytes.length && 
            (bytesRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += bytesRead;
         }

         System.out.println("The offset = " + offset);

      } catch (IOException ie){
         System.err.println("Could not perfomr IO Operation: " + ie);
      }finally {
         try{
            if (is != null) {
               is.close();
            }
         }catch (IOException ie){
            System.err.println("Could not perfomr IO Operation: " + ie);
         }
      }

   }

 }




blog comments powered by Disqus