2015-11-02 55 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文件。