【问题标题】:Android - open file from phone memory using intentAndroid - 使用意图从手机内存中打开文件
【发布时间】:2018-10-09 04:09:10
【问题描述】:

我正在开发一个应用程序,该应用程序将手机中的 .txt 文件作为输入并将其打印在 TextView 上,

public class MainActivity extends AppCompatActivity {
Button button;
Intent intent;private StringBuilder text = new StringBuilder();



private InputStream getResources(String s) {
    return null;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.btn);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("text/plain");
            startActivityForResult(intent, 7);
            Log.v("###", "parent "  + getParent());
        }

    });
} @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    String Fpath = data.getDataString();
  //  final String fileName = ""+Fpath;
    Log.v("###", "yo " +Fpath);

    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
        case 7:

            if (resultCode == RESULT_OK) {
                setContentView(R.layout.activity_main);


                Log.v("###", "hellow");
                setContentView(R.layout.activity_main);
                BufferedReader reader = null;

                try {

                    reader = new BufferedReader(

             new InputStreamReader(getAssets().open("filename.txt")));
                    //change code
                    // do reading
                    String mLine;
                    while ((mLine = reader.readLine()) != null) {
                        text.append(mLine);
                        text.append('\n');
                    }
                } catch (IOException e) {
                    String PathHolder = data.getData().getPath();
                    Toast.makeText(MainActivity.this, PathHolder, Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                } finally {


                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            //log the exception
                        }
                    }

                    TextView output = (TextView) findViewById(R.id.Txt);
                    output.setText((CharSequence) text);

                }
            }
    }
}
}

一切都很好,但线

new InputStreamReader(getAssets().open("filename.txt")));

从 Assets 文件夹中获取文件, 帮我从我的手机中获取文件,

Assets 文件夹中的文件正常打开,但我希望从我的手机中选择它

【问题讨论】:

标签: java android bufferedreader


【解决方案1】:

您可以在onActivityResult 中获取您从文件管理器中选择的文件路径。

 Uri PathHolder = data.getData();

更新

上面一行给出了你从存储中选择的文件的uri。然后您可以轻松地从该 Uri 中获取 File。

忘了getAssets 使用以下方法从文件中读取。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Uri PathHolder = data.getData();
    FileInputStream fileInputStream = null;
    StringBuilder text = new StringBuilder();
    try {
        InputStream inputStream = getContentResolver().openInputStream(PathHolder);
        BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
        String mLine;
        while ((mLine = r.readLine()) != null) {
            text.append(mLine);
            text.append('\n');
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

【讨论】:

  • 问题出在 getAssets 方法中,我认为该方法仅适用于 assets 文件夹,
  • 但是为什么你使用 getAssets 从存储中获取文件呢?
  • getAssets() 仅用于与资产交互。
  • 因为不知道应该用什么
  • 检查我编辑的答案。
【解决方案2】:

你可以试试这个方法:

 public static String getMimeType(String url) {
    String type = null;
    String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    if (extension != null) {
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }
    return type;
}

 public static Uri getFileUri(String filePath) {
    Uri fileUri = null;
    File file = new File(filePath);
    try {
        if (Build.VERSION.SDK_INT >= 24) {
            Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
            m.invoke(null);
        }
        fileUri = Uri.fromFile(file);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return fileUri;
}

对于意图:

if (path.endsWith(".txt") || path.endsWith(".TXT")) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(getFileUri(path.trim()), getMimeType(path.trim()));
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        } else
            Toast.makeText(context, "There is no application available to handle your request!!", Toast.LENGTH_SHORT).show();

    } 

【讨论】:

  • 如果我想从手机访问文件而不是项目中的 Assets 文件夹,getAssets() 方法是否已使用完整??
  • 如果你想从资产中读取文件,你可以试试这个stackoverflow.com/a/9544781/6587502
  • 不,我不想以任何其他方式使用资产,因此我可以从手机中获取文件
  • 授予所需权限并从其路径读取该文件
  • 还是,你不明白我想,我要根据我的选择文件我不能给出具体的文件名
【解决方案3】:

您的 onActivityResult 有轻微变化 首先将此代码粘贴到您的活动中。

    public static String getPath(final Context context, final Uri uri) {

            final boolean isKitKat = true;

            // DocumentProvider
            if (DocumentsContract.isDocumentUri(context, uri)) {
                // ExternalStorageProvider
                if (isExternalStorageDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];

                    if ("primary".equalsIgnoreCase(type)) {
                        return Environment.getExternalStorageDirectory() + "/" + split[1];
                    }

                    // TODO handle non-primary volumes
                }
                // DownloadsProvider
                else if (isDownloadsDocument(uri)) {

                    final String id = DocumentsContract.getDocumentId(uri);
                    final Uri contentUri = ContentUris.withAppendedId(
                            Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                    return getDataColumn(context, contentUri, null, null);
                }
                // MediaProvider
                else if (isMediaDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];

                    Uri contentUri = null;
                    if ("image".equals(type)) {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(type)) {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(type)) {
                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }

                    final String selection = "_id=?";
                    final String[] selectionArgs = new String[]{
                            split[1]
                    };

                    return getDataColumn(context, contentUri, selection, selectionArgs);
                }
            }
            // MediaStore (and general)
            else if ("content".equalsIgnoreCase(uri.getScheme())) {
                return getDataColumn(context, uri, null, null);
            }
            // File
            else if ("file".equalsIgnoreCase(uri.getScheme())) {
                return uri.getPath();
            }

            return null;
        }
  public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }
 public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }
  public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }
public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

现在将您的 onActivityResult 更改为此。

  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
//                String pickedImage = data.getData().getPath();
                String dataString = getPath(this, Uri.parse(data.getDataString()));
                Log.i(TAG, "onActivityResult: pathholder " + dataString);
                File file = new File(dataString);//
                FileInputStream fis = null;
                Log.i(TAG, "onActivityResult: file " + file.getName());
/**if you get the uri(path) then add this following code that i given below*/
                try {
                    fis = new FileInputStream(file.getAbsolutePath());
                    InputStreamReader isr = new InputStreamReader(fis);
                    BufferedReader bufferedReader = new BufferedReader(isr);
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        sb.append(line).append("\n");

                    }
                    Log.i(TAG, "onActivityResult: pathholder " + sb.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }



            }
        }
    }

【讨论】:

  • 你在开玩笑吗
  • 我在项目中没有任何文件我想在点击时获取文件
  • 好的,那么你必须调用意图并添加读写权限。我将发布如何做到这一点。
  • 等待那一刻
  • 现在请检查代码..我已更改 onActivity 结果...我现在正在使用此代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-23
相关资源
最近更新 更多