接收共享文件

时间:2017-06-30 14:57:26

标签: android android-intent share

我在接收.txt文件时遇到问题,在这种情况下是什么应用。
我明白了我的活动:

//check intent
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();

控制是否为ACTION_SEND,通过extra提取Bundle,创建新的File并尝试将其转换为String:< BR />

if (Intent.ACTION_SEND.equals(action) && Objects.equals (type, "text/plain")) {
    Log.d ("Intent", "have shared");
    Bundle bundle = intent.getExtras ();
    Uri uri = (Uri) bundle.get(Intent.EXTRA_STREAM);
    Log.d ("uri ",
    uri.getAuthority ()+" "+
    uri.getPath ()+" "+
    uri.getFragment ()+" "+
    uri.getUserInfo ());
    File file = new File (uri.getPath ());
    Log.d("file" , file.toString ()+" "+file.getPath ()+" "+file.getName ()+" "+ file.exists ()+" "+ file.isFile ()+" "+file.isDirectory ()+" "+file.isAbsolute ()+" "+file.isHidden ());
    try {
        StringBuilder text = new StringBuilder();
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
        //read line by line
        while ((line = br.readLine()) != null) {
             text.append(line);
             text.append('\n');
        }
        Log.d ("String", text.toString ());
        } catch (java.io.IOException e) {
              e.printStackTrace ();
        }

调试日志的结果是:

D/uri: com.whatsapp.provider.media /item/95 null null
D/file: /item/95 /item/95 95 false false false true false

我在BufferedReader

上收到此错误
W/System.err: java.io.FileNotFoundException: /item/95: open failed: ENOENT (No such file or directory)

我不明白为什么 有人能帮助我吗?

1 个答案:

答案 0 :(得分:2)

您没有获得文件的路径。您将获得UriUri不是文件,您的Uri专门设有content计划,而不是file计划。

删除File file = new File (uri.getPath ());。将new FileReader(file)替换为new InputStreamReader(getContentResolver().openInputStream(uri)),以处理contentfile计划。