我怎样才能读取Android的一个文本文件? [英] How can I read a text file in Android?
问题描述
我想读的文本文件中的文本。在下面的code,发生异常(这意味着它转到抓
块)。我把文本文件中的应用程序文件夹。我应该在哪里把这个文本文件(mani.txt),以便正确地读呢?
尝试
{
InputStream的河道= openFileInput(E:\\测试\\ \\ SRC COM \\ \\测试mani.txt);
如果(河道!= NULL)
{
InputStreamReader的inputreader =新的InputStreamReader(河道);
的BufferedReader buffreader =新的BufferedReader(inputreader);
串线,一号线=;
尝试
{
而((行= buffreader.readLine())!= NULL)
第1行+ =行;
}赶上(例外五)
{
e.printStackTrace();
}
}
}
赶上(例外五)
{
字符串错误=;
错误= e.getMessage();
}
试试这个:
我假设你的文本文件是在SD卡上
//查找目录使用API SD卡
// *不*硬code/ SD卡
文件SD卡= Environment.getExternalStorageDirectory();
//获取文本文件
档案文件=新的文件(SD卡,文件file.txt);
//从文件中读取文本
StringBuilder的文本=新的StringBuilder();
尝试 {
的BufferedReader BR =新的BufferedReader(新的FileReader(文件));
串线;
而((行= br.readLine())!= NULL){
text.append(线);
text.append('\ N');
}
br.close();
}
赶上(IOException异常E){
//你需要在这里添加正确的错误处理
}
//查找其ID的观点
TextView的电视=(TextView中)findViewById(R.id.text_view);
//设置文本
tv.setText(text.toString());
以下链接也可以帮助你:
<一个href="http://stackoverflow.com/questions/2902689/how-can-i-read-a-text-file-from-the-sd-card-in-android">How我可以读取SD卡中的Android文本文件?
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();
}
try this :
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('\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());
following links can also help you :
How can I read a text file from the SD card in Android?
How to read text file in Android?
Android read text raw resource file
这篇关于我怎样才能读取Android的一个文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!