Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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

import java.io.IOException;

import android.content.Context;

public class Main {
    private static Context sCurrentContext;

    /**
     * <pre>
     * Read binary data from file stored in app 's cache folder.
     * </pre>
     * @param relativePath relative path to source file
     * @return binary data
     */
    public static byte[] readCacheFile(String relativePath) throws IOException {
        return readFile(getCacheAsbPath(relativePath));
    }

    /**
     * <pre>
     * Read binary data from arbitrary file.
     * </pre>
     * @param absolutePath absolute path to source file
     * @return binary data
     */
    public static byte[] readFile(String absolutePath) throws IOException {
        File file = new File(absolutePath);
        if (!file.exists()) {
            return null;
        }

        FileInputStream in = new FileInputStream(file);
        byte[] b = new byte[in.available()];
        in.read(b);
        in.close();

        return b;
    }

    /**
     * <pre>
     * Get absolute path in app 's cache folder from relative path.
     * </pre>
     */
    public static String getCacheAsbPath(String relativePath) {
        File cacheDir = getCurrentContext().getCacheDir();
        return cacheDir.getAbsolutePath().concat("/").concat(relativePath);
    }

    /**
     * <pre>
     * Get current context of the app. This method resolves the inconvenience of Android which requires context for most of its API.
     * If no activity is resumed, this method returns application context. Otherwise, this method returns last resumed activity.
     * </pre>
     */
    public static Context getCurrentContext() {
        return sCurrentContext;
    }
}