RSS*_*SSS 63 android android-sdcard
我是Android开发的新手.
我需要从SD卡读取文本文件并显示该文本文件.有没有办法直接在Android中查看文本文件,或者我如何阅读和显示文本文件的内容?
Dav*_*ebb 122
在您的布局中,您需要一些东西来显示文本.A TextView是显而易见的选择.所以你会有这样的事情:
<TextView
android:id="@+id/text_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
Run Code Online (Sandbox Code Playgroud)
你的代码看起来像这样:
//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);
Run Code Online (Sandbox Code Playgroud)
这可能会出现在onCreate()您Activity或其他地方的方法中,具体取决于您想要做什么.
回应
不要硬编码/ SD卡/
有时候,我们不得不硬编码在某些型号的手机API方法返回内部手机内存.
已知类型:HTC One X和Samsung S3.
Environment.getExternalStorageDirectory().getAbsolutePath()给出了一个不同的路径--Android
| 归档时间: |
|
| 查看次数: |
148815 次 |
| 最近记录: |