Chr*_*att 5 java android text file android-intent
我有一个Uri
指向来自 an 的文本文件intent
,我正在尝试读取该文件以解析其中的字符串。这是我尝试过的,但失败了FileNotFoundException
。该toString()
方法似乎失去了/
java.io.FileNotFoundException: content:/com.google.android.apps.bigtop/attachments/downloads/528c4088144d1515d933ca406b7bc273/attachments/d_0_0_b562310a_52b6ec1c_c4d53f20d.txt 或 openNo.txt1800000000 文件失败
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();
}
}
Run Code Online (Sandbox Code Playgroud)
数据的价值是:
content://com.google.android.apps.bigtop/attachments/downloads/528c4088144d1515d933ca406b7bc273/attachments/d_0_0_b562310a_52b6ec1c_c4d5f0d3_73f7110d3_73f71289atxt%
而 data.getPath() 的值是
/attachments/downloads/528c4088144d1515d933ca406b7bc273/attachments/d_0_0_b562310a_52b6ec1c_c4d5f0d3_73f7489a_711e4cf2/undtitle
我现在试图直接从 Uri 而不是路径获取文件:
Uri data = getIntent().getData();
String text = data.toString();
//...
File f = new File(text);
Run Code Online (Sandbox Code Playgroud)
但是 f 似乎丢失了 content:// 中的斜杠之一
F:
内容:/com.google.android.apps.bigtop/attachments/downloads/528c4088144d1515d933ca406b7bc273/attachments/d_0_0_b562310a_52b6ec1c_c4d5f0d3_73f7120d3_73f7120d3_73f712fc273
Bey*_*yaz 12
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) {
}
Run Code Online (Sandbox Code Playgroud)
Hir*_*tel -2
从文件中读取文本:
private String readText() {
File f = new File(Your_File_Path);
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1) {
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
Run Code Online (Sandbox Code Playgroud)
该函数将返回 String,根据您的要求使用它。
使用如下:
Log.i("Text from File", readText());
Run Code Online (Sandbox Code Playgroud)
完毕