我想从文本文件中读取文本。在下面的代码中,发生了一个异常(这意味着它进入了 catch
block )。我将文本文件放在应用程序文件夹中。我应该把这个文本文件(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());
以下链接也可以帮助您:
How can I read a text file from the SD card in Android?
关于java - 如何在 Android 中读取文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12421814/