我有一个指向文本文件的Uri,来自于一个intent,我正在尝试读取文件以解析其中的字符串。这是我尝试过的内容,但它失败了并显示FileNotFoundException。toString()方法似乎会丢失“/”。
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();
}
}
数据的值为:
content://com.google.android.apps.bigtop/attachments/downloads/528c4088144d1515d933ca406b7bc273/attachments/d_0_0_b562310a_52b6ec1c_c4d5f0d3_73f7489a_711e4cf2/untitled%20text.txt
而数据的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://中丢失了一个斜杠
f:
content:/com.google.android.apps.bigtop/attachments/downloads/528c4088144d1515d933ca406b7bc273/attachments/d_0_0_b562310a_52b6ec1c_c4d5f0d3_73f7489a_711e4cf2/untitled%20text.txt
InputStream is = getContentResolver().openInputStream(uri)
获取内容。请参阅http://developer.android.com/reference/android/content/ContentResolver.html#openInputStream%28android.net.Uri%29。 - Andrei Mărcuţ