事務屋さんの備忘録

主にプログラミングのことを書いていきます。メモというか備忘録的な感じで。プログラミングといっても、私はプロのエンジニアでも本職のプログラマーでもありません。単なる事務職をやってるサラリーマンで、空いた時間にちょこちょこっとプログラミングしてる程度です。よってこのブログに記載したことが誤っていたり、もっとよい方法がある場合もあると思います。その場合には、ご指摘いただけると嬉しいです。また、このブログを読んで役に立った、なんて方がいらっしゃったら幸いですね。

Androidでassetsフォルダ内にあるcsvデータをパースする

メモ。

package com.example.textfile02;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

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

public class MainActivity extends Activity {
	
	private TextView textView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		textView = (TextView) findViewById(R.id.textView1);
		
		CSVParser csvParser = new CSVParser(this, "csvtest01.txt");
		csvParser.parse();
		
	}
	
	public class CSVParser {
		
		private Context context;
		private String file;
		
		public CSVParser(Context context, String file){
			this.file = file;
			this.context = context;
		}

		public void parse() {
			// AssetManagerの呼び出し
			AssetManager assetManager = context.getResources().getAssets();
			try {
				// CSVファイルの読み込み
				InputStream is = assetManager.open(file);
				InputStreamReader inputStreamReader = new InputStreamReader(is);
				BufferedReader bufferReader = new BufferedReader(inputStreamReader);
				String line = "";
				String txt = "";
				
				while ((line = bufferReader.readLine()) != null) {
					
					// 各行が","で区切られていて5つの項目
					StringTokenizer st = new StringTokenizer(line, ",");
					String first = st.nextToken();
					String second = st.nextToken();
					String third = st.nextToken();
					String fourth = st.nextToken();
					String fifth = st.nextToken();
					
					txt = first + " " + second + " " + third + " " + fourth + " " + fifth + "\n";
					
					//文字列を追加する
					textView.append(txt);
					
				}
				
				bufferReader.close();
			
			} catch (IOException e) {
				//e.printStackTrace();
				textView.setText("読み込みに失敗しました・・・");
			}
		}
	}

}