gpt4 book ai didi

android - 从手机上的任何位置读取 .txt 文件

转载 作者:搜寻专家 更新时间:2023-11-01 08:30:47 25 4
gpt4 key购买 nike

在我的应用程序中,我有这段代码允许用户选择一个文件:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com