作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
在我的应用程序中,我有这段代码允许用户选择一个文件:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/plain");
startActivityForResult(intent,1);
用户可以从手机中的任何位置选择 .txt 文件,甚至可以从 google drive 中选择。文件选择完成后,我检索与该文件对应的 Uri 对象。问题是我无法使用此 Uri 来读取文件,因为它无效。这是我的代码:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
File file = new File(uri.toString());
try{
InputStream inputStream = new FileInputStream(file);
int content;
while ((content = inputStream.read()) != -1) {
Log.d("===>", String.valueOf((char) content));
}
}catch (Exception e){
Log.d("===>", e.toString());
}
}
}
}
我总是得到 fileNotFoundException。我的问题是,有没有办法读取选定的文件(事先不知道文件的来源)。如果没有,有没有办法将所选文件复制到我可以轻松获取的文件夹中?
最佳答案
The problem is I can't use this Uri to read the file because it is not valid.
那是因为 Uri
不是文件。
is there a way to read the selected file (without knowing in advance the location it will come from)
用户没有选择文件。用户选择了一段内容。
要使用 Uri
表示的内容,调用 ContentResolver
上的 openInputStream()
,传入 Uri
。这为您提供了一个可用于读取内容的 InputStream
。
关于android - 从手机上的任何位置读取 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41077264/
我是一名优秀的程序员,十分优秀!