android

时间:2015-11-02 11:53:00

标签: android android-activity android-studio

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

1 个答案:

答案 0 :(得分: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文件。