How to convert File into an array of bytes
Published: April 6, 2010 , Updated: March 30, 2010 , Author: mkyong
The Java.io.FileInputStream can used to convert a File object into an array of bytes. In this example, you read a file from “C:\\testing.txt“, convert it into an array of bytes and print out the content.
package com.mkyong.common; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; public class FileToArrayOfBytes { public static void main( String[] args ) { 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(); } } }
Any Java questions or problems? please post at this JavaNullPointer.com forum, see you there ~