如何在 Android 中从 SD 卡读取文本文件?
我是 Android 开发新手。
我需要从 SD 卡读取文本文件并显示该文本文件。 有没有办法直接在Android中查看文本文件,或者如何读取和显示文本文件的内容?
I am new to Android development.
I need to read a text file from the SD card and display that text file.
Is there any way to view a text file directly in Android or else how can I read and display the contents of a text file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
在你的布局中你需要一些东西显示文本。
TextView
是显而易见的选择。所以你会得到这样的东西:你的代码将如下所示:
这可以放在
Activity
的onCreate()
方法中,或者其他地方,具体取决于你想做什么。In your layout you'll need something to display the text. A
TextView
is the obvious choice. So you'll have something like this:And your code will look like this:
This could go in the
onCreate()
method of yourActivity
, or somewhere else depending on just what it is you want to do.回应
有时我们必须对其进行硬编码,因为在某些手机型号中,API 方法会返回内部手机内存。
已知类型:HTC One X 和三星 S3。
Environment.getExternalStorageDirectory().getAbsolutePath() 给出不同的路径 - Android
In response to
Sometimes we HAVE TO hardcode it as in some phone models the API method returns the internal phone memory.
Known types: HTC One X and Samsung S3.
Environment.getExternalStorageDirectory().getAbsolutePath() gives a different path - Android
您应该具有 READ_EXTERNAL_STORAGE 权限才能读取 SD 卡。
在manifest.xml中添加权限
从android 6.0或更高版本开始,您的应用程序必须要求用户在运行时授予危险权限。请参考这个链接
权限概述
You should have READ_EXTERNAL_STORAGE permission for reading sdcard.
Add permission in manifest.xml
From android 6.0 or higher, your app must ask user to grant the dangerous permissions at runtime. Please refer this link
Permissions overview
请注意:有些手机有 2 张 SD 卡,一张内置固定卡和一张可移动卡。
您可以通过标准应用程序找到最后一个的名称:“Mijn Bestanden”(英文:“MyFiles”?)
当我打开这个应用程序(项目:所有文件)时,打开的文件夹的路径是“/sdcard”,向下滚动有一个条目“external-sd”,单击它会打开文件夹“/sdcard/external_sd/”。
假设我想打开一个文本文件“MyBooks.txt”,我会使用以下内容:
Beware: some phones have 2 sdcards , an internal fixed one and a removable card.
You can find the name of the last one via a standard app:"Mijn Bestanden" ( in English: "MyFiles" ? )
When I open this app (item:all files) the path of the open folder is "/sdcard" ,scrolling down there is an entry "external-sd" , clicking this opens the folder "/sdcard/external_sd/" .
Suppose I want to open a text-file "MyBooks.txt" I would use something as :
不幸的是,所有这些答案都是无用的,因为自 Android 11 (API 30) 以来就已经过时了。由于 Google 政策(我不明白),从那时起,对内部或 SD 卡的文件访问受到严格限制,这种方式并不真正明智:
All of these answers are unfortunately useless, because outdated since Android 11 (API 30). Due to Google policy, that I do not appreciate, file access to internal or SD card is since then strictly limited in a way that is not really sensible: