Android从URI读取文本文件



我有一个指向intent的文本文件的Uri,我正在尝试读取该文件以解析其中的字符串。这是我尝试过的,但FileNotFoundException失败了。toString()方法似乎丢失了一个/

java.io.FileNotFoundException:content:/com.google.android.apps.bigtop/attactions/downloads/528c4088144d1515d933ca406b7bc273/attactions/d_0_b562310a_2b6ec1c_c4d5f0d3_73f7489a_711e4cf2/untitled%20text.txt:打开失败:ENOENT(没有这样的文件或目录)

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

data.getPath()的值为

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

我现在正试图直接从Uri而不是路径获取文件:

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

但是f似乎丢失了内容中的一个斜杠://

f:

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

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

文件读取文本

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

此函数将返回String,并根据您的要求使用它。

使用如下:

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

完成

相关内容

  • 没有找到相关文章

最新更新