Friday, 22 April 2016

How to convert file into an array of bytes ?


Convert File into an array of bytes
FileInputStream fileInputStream = null;
File file = new File("C:\\testing.txt");
byte[] bFile = new byte[(int) file.length()];

try {
  // Convert file into array of bytes
  fileInputStream = new FileInputStream(file);
  fileInputStream.read(bFile);
  fileInputStream.close();
  for (int i = 0; i < bFile.length; i++) {
   System.out.print((char)bFile[i]);
  }
  System.out.println("Done");
}catch(Exception e){
  e.printStackTrace();

}


Convert array of bytes into File
FileInputStream fileInputStream=null;
File file = new File("C:\\testing.txt");
byte[] bFile = new byte[(int) file.length()];
try {
  //convert file into array of bytes
  fileInputStream = new FileInputStream(file);
  fileInputStream.read(bFile);
  fileInputStream.close();
  //convert array of bytes into file
  FileOutputStream fileOuputStream = new FileOutputStream("C:\\testing2.txt");
  fileOuputStream.write(bFile);
  fileOuputStream.close();
  System.out.println("Done");
}catch(Exception e){
  e.printStackTrace();
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.