Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Read Text File from URI

I've got a Uri pointing to a text file from an intent and I'm trying to read the file to parse the string inside it. This is what I've tried but it's failing with FileNotFoundException. The toString() method appears to lose a /

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();
    }
}

The value of data is:

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

and the value of data.getPath() is

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

I'm now trying to get the file directly from the Uri rather than the path:

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

But f appears to lose one of the slashes from content://

f:

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

like image 663
Chris Byatt Avatar asked Jun 26 '15 09:06

Chris Byatt


1 Answers

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) {

        }
like image 124
Ucdemir Avatar answered Oct 08 '22 19:10

Ucdemir