【问题标题】:Text file(.txt) in androidandroid中的文本文件(.txt)
【发布时间】:2015-11-02 11:52:59
【问题描述】:

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

【问题讨论】:

标签: android android-activity android-studio


【解决方案1】:

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 文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-03
    • 2023-02-24
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    • 2021-02-23
    • 1970-01-01
    相关资源
    最近更新 更多