gpt4 book ai didi

java - Android 从 URI 读取文本文件

转载 作者:太空宇宙 更新时间:2023-11-03 11:24:57 27 4
gpt4 key购买 nike

我有一个 Uri 指向来自 intent 的文本文件,我正在尝试读取该文件以解析其中的字符串。这是我尝试过的方法,但因 FileNotFoundException 而失败。 toString() 方法似乎丢失了一个 /

java.io.FileNotFoundException: content:/com.google.android.apps.bigtop/attachments/downloads/528c4088144d1515d933ca406b7bc273/attachments/d_0_0_b562310a_52b6ec1c_c4d5f0d3_73f7489a_711e4cf2/untitled%20text.txt: open failed: ENOENT (No such file or directory)

Uri data = getIntent().getData();
String text = data.toString();
if(data != null) {

try {
File f = new File(text);
FileInputStream is = new FileInputStream(f); // Fails on this line
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
Log.d("attachment: ", text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

数据的值(value)是:

content://com.google.android.apps.bigtop/attachments/downloads/528c4088144d1515d933ca406b7bc273/attachments/d_0_0_b562310a_52b6ec1c_c4d5f0d3_73f7489a_711e4cf2/untitled%20text.txt

data.getPath()的值是

/attachments/downloads/528c4088144d1515d933ca406b7bc273/attachments/d_0_0_b562310a_52b6ec1c_c4d5f0d3_73f7489a_711e4cf2/untitled text.txt

我现在尝试直接从 Uri 而不是路径获取文件:

Uri data = getIntent().getData();
String text = data.toString();
//...
File f = new File(text);

但是 f 似乎丢失了 content://

中的斜杠之一

:

content:/com.google.android.apps.bigtop/attachments/downloads/528c4088144d1515d933ca406b7bc273/attachments/d_0_0_b562310a_52b6ec1c_c4d5f0d3_73f7489a_711e4cf2/untitled%20text.txt

最佳答案

Uri uri = data.getData();

try {
InputStream in = getContentResolver().openInputStream(uri);


BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder total = new StringBuilder();
for (String line; (line = r.readLine()) != null; ) {
total.append(line).append('\n');
}

String content = total.toString();



}catch (Exception e) {

}

关于java - Android 从 URI 读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31069556/

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