如何在 Android 中读取文本文件? [英] How can I read a text file in Android?
本文介绍了如何在 Android 中读取文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从文本文件中读取文本.在下面的代码中,发生了异常(这意味着它进入了 catch
块).我将文本文件放在应用程序文件夹中.我应该把这个文本文件 (mani.txt) 放在哪里才能正确阅读?
I want to read the text from a text file. In the code below, an exception occurs (that means it goes to the catch
block). I put the text file in the application folder. Where should I put this text file (mani.txt) in order to read it correctly?
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 卡上
I assume your text file is on sd card
//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('
');
}
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());
以下链接也可以帮助您:
following links can also help you :
这篇关于如何在 Android 中读取文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文