如何在Android中阅读文本文件?

我想从文本文件中读取文本。在下面的代码中,发生异常(这意味着它进入了该catch块)。我将文本文件放在应用程序文件夹中。我应该在哪里放置此文本文件(mani.txt)以便正确阅读?

    try

{

InputStream instream = openFileInput("E:\\test\\src\\com\\test\\mani.txt");

if (instream != null)

{

InputStreamReader inputreader = new InputStreamReader(instream);

BufferedReader buffreader = new BufferedReader(inputreader);

String line,line1 = "";

try

{

while ((line = buffreader.readLine()) != null)

line1+=line;

}catch (Exception e)

{

e.printStackTrace();

}

}

}

catch (Exception e)

{

String error="";

error=e.getMessage();

}

回答:

我假设你的文本文件在SD卡上

//Find the directory for the SD Card using the API

//Don’t hardcode “/sdcard”

File sdcard = Environment.getExternalStorageDirectory();

//Get the text file

File file = new File(sdcard,”file.txt”);

//Read text from file

StringBuilder text = new StringBuilder();

try {

BufferedReader br = new BufferedReader(new FileReader(file));

String line;

while ((line = br.readLine()) != null) {

text.append(line);

text.append('\n');

}

br.close();

}

catch (IOException e) {

//You’ll need to add proper error handling here

}

//Find the view by its id

TextView tv = (TextView)findViewById(R.id.text_view);

//Set the text

tv.setText(text.toString());

以上是 如何在Android中阅读文本文件? 的全部内容, 来源链接: utcz.com/qa/422465.html

回到顶部