Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.io.ByteArrayOutputStream;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;

public class Main {
    public static String readFromFileOrAssets(Context context, String fileName) throws IOException {
        String jsonData;
        //  FIXME: Check for file existence - do not use exception for control flow
        try {
            jsonData = readFromFileInput(context, fileName);
        } catch (FileNotFoundException e) {
            jsonData = readFromAssets(context, fileName);
        }
        return jsonData;
    }

    public static String readFromFileInput(Context context, String fileName) throws IOException {

        InputStream inputStream = context.openFileInput(fileName);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int i;
        try {
            i = inputStream.read();
            while (i != -1) {
                byteArrayOutputStream.write(i);
                i = inputStream.read();
            }
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return byteArrayOutputStream.toString();
    }

    public static String readFromAssets(Context context, String fileName) throws IOException {

        InputStream inputStream = context.getAssets().open(fileName);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int i;
        try {
            i = inputStream.read();
            while (i != -1) {
                byteArrayOutputStream.write(i);
                i = inputStream.read();
            }
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return byteArrayOutputStream.toString();
    }
}