【发布时间】:2015-11-05 14:19:23
【问题描述】:
我在我的电脑上创建了一个文件,我希望我的应用可以从中读取。
如何在我的应用中读取该文件?
谢谢
【问题讨论】:
我在我的电脑上创建了一个文件,我希望我的应用可以从中读取。
如何在我的应用中读取该文件?
谢谢
【问题讨论】:
将文件放入assets/(例如,在典型的Android Studio 项目中为app/src/main/assets/)。然后在AssetManager 上使用open() 以在该内容上获得InputStream。您可以通过调用getAssets() 从您的Activity 或其他Context 获取AssetManager。
【讨论】:
将文件移动到卡片并添加路径而不是“file.txt”
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);
如果您想阅读文本,这是最好的例子
【讨论】: