ここに私があなたのニーズに合うようにバッファリングされた読み取り拡張/変更のアクティビティで何をするかがあります
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt")));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
...
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
編集:あなたの質問が活動の外でそれを行う方法についてである場合、私の答えはおそらく役に立たないです。あなたの質問が単にアセットからファイルを読み取る方法であるならば、答えは上記です。
更新:
タイプを指定してファイルを開くには、次のようにInputStreamReader呼び出しにタイプを追加するだけです。
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt"), "UTF-8"));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
...
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
編集
@Stanがコメントで言っているように、私が提供しているコードは行を合計していません。mLineパスごとに置き換えられます。それが私が書い//process lineた理由です。ファイルにはある種のデータ(連絡先リストなど)が含まれており、各行は個別に処理する必要があると思います。
何も処理せずに単にファイルをロードしたい場合はmLine、各パスを使用StringBuilder()および追加して、各パスで合計する必要があります。
別の編集
@Vincentのコメントによると、私はfinallyブロックを追加しました。
また、Java 7以降でtry-with-resourcesは、AutoCloseableおよびを使用できます。Closeableは、最近のJavaの機能ます。
環境
コメントで@LunarWatcher getAssets()はそれがclassinであることを指摘しcontextます。したがって、外部で呼び出す場合activityは、それを参照して、コンテキストインスタンスをアクティビティに渡す必要があります。
ContextInstance.getAssets();
これは@Maneeshの回答で説明されています。それで、これがあなたに役立つ場合は、彼の答えを賛成投票してください。