Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

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 {
    /**
     * 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);
    }
}