Encodes a file to a base 64 string - Android android.util

Android examples for android.util:Base64

Description

Encodes a file to a base 64 string

Demo Code


//package com.java2s;
import java.io.File;
import java.io.FileNotFoundException;

import java.io.IOException;
import java.io.RandomAccessFile;
import android.util.Base64;

public class Main {
    /**/*from   w w  w . java  2  s. co  m*/
     * Encodes a file to a base 64 string
     * @param file
     * @return The encoded string
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static String binaryToBase64(File file)
            throws FileNotFoundException, IOException {

        String base64String;
        RandomAccessFile raFile = new RandomAccessFile(file, "r");

        // Creating a bytes array with the video length
        long length = raFile.length();
        byte[] binaryVideo = new byte[(int) length];

        try {
            raFile.readFully(binaryVideo);
        } finally {
            // Closing stream read
            raFile.close();
        }

        // To base 64
        base64String = Base64.encodeToString(binaryVideo,
                (Base64.URL_SAFE + Base64.NO_WRAP));

        // Returning the video as a base 64 string
        return base64String;
    }
}

Related Tutorials