Android Read Text File from URI
I have Uri
one pointing to a text file from intent
and I am trying to read the file to parse the line inside it. This is what I tried but with error FileNotFoundException
. It looks like the method is toString()
losing/
java.io.FileNotFoundException: content: /com.google.android.apps.bigtop/attachments/downloads/528c4088144d1515d933ca406b7bc273/attachments/d_0_0_b562310a_52b6ec1c_c4d5f7484d3_73funt
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();
}
}
Data value:
Contents: //com.google.android.apps.bigtop/attachments/downloads/528c4088144d1515d933ca406b7bc273/attachments/d_0_0_b562310a_52b6ec1c_c4d5f0d3_73f7489a_711e420cf2/unt
and the data.getPath () value is
/ attachments / downloads / 528c4088144d1515d933ca406b7bc273 / attachments / d_0_0_b562310a_52b6ec1c_c4d5f0d3_73f7489a_711e4cf2 / untitled text.txt
Now I am trying to get the file directly from the Uri and not along the path:
Uri data = getIntent().getData();
String text = data.toString();
//...
File f = new File(text);
But f seems to lose one of the traits from the content: //
F:
Contents: /com.google.android.apps.bigtop/attachments/downloads/528c4088144d1515d933ca406b7bc273/attachments/d_0_0_b562310a_52b6ec1c_c4d5f0d3_73f7489a_711e420cf2.unt
source to share
Read text from File :
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();
}
This function will return a String , use it as your requirement.
Use as below:
Log.i("Text from File", readText());
Done
source to share