使用InputStream读取文本文件

我如何阅读像android app中的文本文件:

"1.something written

2.in this file

3.is to be read by

4.the InputStream

..."

所以我可以返回一个字符串,如:

"something written\nin this file\nis to be read by\nthe InputStream"

我想到的是(伪代码):

make an inputstream

is = getAssest().open("textfile.txt"); //in try and catch

for loop{

string = is.read() and if it equals "." (i.e. from 1., 2., 3. etc) add "/n" ...

}

回答:

试试这个

import android.app.Activity;

import android.os.Bundle;

import android.widget.Toast;

import java.io.*;

public class FileDemo1 extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

try {

playWithRawFiles();

} catch (IOException e) {

Toast.makeText(getApplicationContext(), "Problems: " + e.getMessage(), 1).show();

}

}

public void playWithRawFiles() throws IOException {

String str = "";

StringBuffer buf = new StringBuffer();

InputStream is = this.getResources().openRawResource(R.drawable.my_base_data);

try {

BufferedReader reader = new BufferedReader(new InputStreamReader(is));

if (is != null) {

while ((str = reader.readLine()) != null) {

buf.append(str + "\n" );

}

}

} finally {

try { is.close(); } catch (Throwable ignore) {}

}

Toast.makeText(getBaseContext(), buf.toString(), Toast.LENGTH_LONG).show();

}

}

以上是 使用InputStream读取文本文件 的全部内容, 来源链接: utcz.com/qa/426392.html

回到顶部