2015-11-02 64 views
-1

我是android开发新手。我可以在我的应用程序中添加.txt文件,并使用它在我的活动中显示文本(文本文件包含一段描述),而不是在我的strings.XML文件中编写整个描述。如果是,请帮我编写代码。由于android中的文本文件(.txt)

+1

尝试此:http://stackoverflow.com/a/8695590/3110234 – activesince93

+0

可能重复[如何读取.txt并显示为Android中的TextView?](http://stackoverflow.com/questions/) 8695361/how-can-i-read-txt-and-display-it-as-textview-in-android) –

+0

@activesince93我想在我的项目中添加.txt文件,如资产或原始文件夹而非SD卡 –

回答

0

There are a few decent answers to this in this question

//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()); 

除非这一点是依赖于从可能改变.txt文件阅读,你一定要尝试使用字符串的XML文件。