来自URI

时间:2015-06-26 09:25:47

标签: java android file android-intent text

我有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)< / p>

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

数据的价值是:

  

内容://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://

中的一个斜杠

F:

  

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

2 个答案:

答案 0 :(得分:0)

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

        }

答案 1 :(得分:-1)

文件

阅读文字

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

此功能将返回 字符串,并将其用作您的要求。

使用如下:

Log.i("Text from File", readText());

完成