Convert any file into byte array or byte array into string in Android

How to convert image or video file into byte[] or byte[] into String in Android:

TO upload image, video or any other file on server fro Android app we need to convert that image / video file to string or upload byte by byte.

Note: this method is suite able for small files (image, video, pdf etc).

Download latest version of commons-io from this link http://commons.apache.org/io/download_io.cgi

Unzip downloaded file. Include commons-io-2.4.jar (2.4 is it’s current version, in future it will be different) in your Android project. Learn how to include external jar file in eclipse for Android.

This code describe how to convert a file into byte array or byte array into string.

[sociallocker]

public String convertFileToString(String pathOnSdCard){

 

String strFile=null;

File file=new File(pathOnSdCard);

try {

byte[] data = FileUtils.readFileToByteArray(file);//Convert any file, image or video into byte array

strFile = Base64.encodeToString(data, Base64.NO_WRAP);//Convert byte array into string

} catch (IOException e) {

e.printStackTrace();

}

return strFile;

}

[/sociallocker]

Leave a comment

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