Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.BufferedInputStream;

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

import android.util.Base64;

public class Main {
    public static String bytesToBinary(File file) {
        String fileStr = "";
        try {
            byte[] bts = getFileBytes(file);
            fileStr = Base64.encodeToString(bts, Base64.DEFAULT);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return fileStr;
    }

    public static byte[] getFileBytes(File file) throws IOException {
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            int bytes = (int) file.length();
            byte[] buffer = new byte[bytes];
            int readBytes = bis.read(buffer);
            if (readBytes != buffer.length) {
                throw new IOException("Entire file not read");
            }
            return buffer;
        } finally {
            if (bis != null) {
                bis.close();
            }
        }
    }
}