Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//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.content.Context;

import android.text.TextUtils;

public class Main {
    private static final int BUF_SIZE = 1024;

    public static String loadString(Context context, String filename) {
        if (context == null || TextUtils.isEmpty(filename))
            return null;
        File file = getFile(context, filename);
        return loadString(file);
    }

    /**
     * read file to a string
     * 
     * @param context
     * @param file
     * @return
     */
    public static String loadString(File file) {
        if (null == file || !file.exists()) {
            return "";
        }
        FileInputStream fis = null;

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            fis = new FileInputStream(file);
            int restSize = fis.available();
            int bufSize = restSize > BUF_SIZE ? BUF_SIZE : restSize;
            byte[] buf = new byte[bufSize];
            while (fis.read(buf) != -1) {
                baos.write(buf);
                restSize -= bufSize;

                if (restSize <= 0)
                    break;
                if (restSize < bufSize)
                    bufSize = restSize;
                buf = new byte[bufSize];
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return baos.toString();
    }

    public static File getFile(Context context, String filename) {
        if (context == null || TextUtils.isEmpty(filename))
            return null;
        return new File(context.getFilesDir().getAbsoluteFile() + filename);

    }
}