get Base64 String From File - Android File Input Output

Android examples for File Input Output:Base64

Description

get Base64 String From File

Demo Code


//package com.java2s;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import java.io.IOException;

import android.util.Base64;

public class Main {
    /**// www .j ava  2  s.  c o  m
     * File to Base64
     * @param filePath
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static String getBase64StringFromFile(String filePath)
            throws FileNotFoundException, IOException {
        byte[] buffer = null;
        File file = new File(filePath);
        FileInputStream fis = null;
        ByteArrayOutputStream bos = null;
        byte[] b = new byte[1000];
        try {
            fis = new FileInputStream(file);
            bos = new ByteArrayOutputStream(1000);
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            throw e;
        } catch (IOException e) {
            throw e;
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }

        return Base64.encodeToString(buffer, Base64.DEFAULT);
    }
}

Related Tutorials