Load a raw string resource. - Android App

Android examples for App:Resource

Description

Load a raw string resource.

Demo Code


//package com.java2s;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.content.Context;

import android.util.Log;

public class Main {
    /**//from   w w  w.j a v  a2 s .c om
     * Load a raw string resource.
     * 
     * @param context
     *            The current context.
     * @param resourceId
     *            The resource id.
     * @return The loaded string.
     */
    private static String getStringFromRawResource(Context context,
            int resourceId) {
        String result = null;

        InputStream is = context.getResources().openRawResource(resourceId);
        if (is != null) {
            StringBuilder sb = new StringBuilder();
            String line;

            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } catch (IOException e) {
                Log.w("ApplicationUtils", String.format(
                        "Unable to load resource %s: %s", resourceId,
                        e.getMessage()));
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    Log.w("ApplicationUtils", String.format(
                            "Unable to load resource %s: %s", resourceId,
                            e.getMessage()));
                }
            }
            result = sb.toString();
        } else {
            result = "";
        }

        return result;
    }
}

Related Tutorials