Loads lines of text from the given path in the assets directory. - Android App

Android examples for App:Resource

Description

Loads lines of text from the given path in the assets directory.

Demo Code

/**********************************************************************
 * Copyright (c) 2015 Luka Kunic, "ActivityUtils.java"
 * /*from w  w w  .ja va2 s  . c  o  m*/
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * 
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for
 * the specific language governing permissions and limitations under the License.
 *
 * Author: lkunic
 * Last modified: 08/02/2015
 **********************************************************************/
//package com.java2s;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;

public class Main {
    /**
     * Loads lines of text from the given path in the assets directory.
     * @param context Application context.
     * @param path Path in the assets folder to the text file to load.
     * @return String array representing lines of text in the file.
     */
    public static String[] loadTextFromAssets(Context context, String path) {
        try {
            // Open the input stream to the text in assets
            InputStream inputStream = context.getAssets().open(path);
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream);
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);

            List<String> lines = new ArrayList<String>();

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                lines.add(line);
            }

            inputStream.close();

            return lines.toArray(new String[lines.size()]);
        } catch (IOException e) {
            return null;
        }

    }
}

Related Tutorials