軽くAssetManager

連日の投稿です。今回はassetsフォルダにあるテキストファイルを読み込んで、TextViewに表示してみようと思います。

やりたいこと

  1. AssetManagerを取得する
  2. assetsフォルダのテキストファイルを読み込む
  3. 読み込んだファイルをTextViewに表示する

こんな感じで読み込んだassets/lorem.txtの内容を表示

実装の要点を下記にまとめます

1. Context#getAssets()メソッドでAssetManagerを取得

AssetManager assets = getAssets();

2. 読み込みたいファイルのassetsフォルダからの相対パス名を引数として渡しInputStreamを取得する

private static final String TEXT_NAME = "lorem.txt";
InputStream is = null;
        
try {
	is = assets.open(TEXT_NAME);
} catch (IOException e) {
	e.printStackTrace();
} 

3. InputStreamをByteArrayOutputStreamに読みこんで、それからStringを作成する

private String getText(InputStream is) throws IOException{
    	ByteArrayOutputStream bs = new ByteArrayOutputStream();
    	byte[] bytes = new byte[4096];
    	int len = 0;
    	while((len = is.read(bytes)) > 0){
    		Log.d(TAG, "len = " + len);
    		bs.write(bytes, 0, len);
    	}
        //テキストファイルがUTF8でエンコードされているので第2引数に指定
    	return new String(bs.toByteArray(), "UTF8");
    }

では実装です

package com.android.practice;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class AssetsTest extends Activity {
    
	private static final String TAG = AssetsTest.class.getSimpleName();
	private static final String TEXT_NAME = "lorem.txt";
	
	private TextView mTextView;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        mTextView = new TextView(this);
        setContentView(mTextView);
        
        //Context#getAssets()メソッドでAssetManagerを取得
        AssetManager assets = getAssets();
        InputStream is = null;
        
        try {
        	//読み込みたいファイルのassetsフォルダからの相対パス名を引数として渡しInputStreamを取得する
			is = assets.open(TEXT_NAME);
			String text = getText(is);
			mTextView.setText(text);
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if(is != null){
				try {
					is.close();
				} catch (IOException e){
					mTextView.setText("Couldn't close file");
				}
			}
		}
    }
    
    //InputStreamをByteArrayOutputStreamに読みこんで、それからStringを作成する
    private String getText(InputStream is) throws IOException{
    	ByteArrayOutputStream bs = new ByteArrayOutputStream();
    	byte[] bytes = new byte[4096];
    	int len = 0;
    	while((len = is.read(bytes)) > 0){
    		Log.d(TAG, "len = " + len);
    		bs.write(bytes, 0, len);
    	}
    	//テキストファイルがUTF8でエンコードされているので第2引数に指定
    	return new String(bs.toByteArray(), "UTF8");
    }
}

assets配下のファイルは案外簡単に取得できました。

HashTag #Java, #Android, #AssetManager, #InputStream, #ByteArrayOutputStream