How to convert a File to ByteArray?

Here a some example to explain how to convert a file to byte[].

  • First example with FileUtils.readFileToByteArray:
package com.nourit.javaIO;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class FileToByteArray {

  public static void main(String[] args) throws IOException {
    // specify your bytes here.
    File file = new File("D:/tmp/nourit.txt");
    byte[] bytesFile = FileUtils.readFileToByteArray(file);
    System.out.println("------------------ Begin of Content ----------------------");
    for (int i = 0; i < bytesFile.length; i++) {
      System.out.print((char) bytesFile[i]);
    }

    System.out.println("------------------ End of Content ----------------------");

    System.out.println("Operation successful!");
  }
}

Output:

------------------ Begin of Content ----------------------
IT Training Center for Java and Web technology. 
If you enjoy and like our tutorials and believe in our mission, 
Please Subscribe us on Youtube and follow us on Twitter, 
or befriend us on Facebook or Google Plus.
------------------ End of Content ----------------------
Operation successful!
  • Second examlpe:
package com.nourit.javaIO;

import java.io.File;

public class FileToByteArray1 {

  public static void main(String[] args) {
    // specify your bytes here.
    File file = new File("D:/tmp/nourit.txt");
    byte[] bytesFile = new byte[(int) file.length()];
    System.out.println("------------------ Begin of Content ----------------------");
    System.out.println(bytesFile.toString());

    System.out.println("------------------ End of Content ----------------------");

    System.out.println("Operation successful!");
  }
}

Output:

------------------ Begin of Content ----------------------
[B@15db9742
------------------ End of Content ----------------------
Operation successful!

 

 

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*