简体   繁体   English

Android-使用意图从手机内存中打开文件

[英]Android - open file from phone memory using intent

I am working on an app that takes the .txt file from a phone as input and prints it on the TextView, 我正在开发一个应用程序,该应用程序将手机中的.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);

                }
            }
    }
}
}

everything is good but the line 一切都很好,但行

new InputStreamReader(getAssets().open("filename.txt"))); 新的InputStreamReader(getAssets()。open(“ filename.txt”))));

Taking the file from Assets folder, Help me to get the file from My phone, 从Assets文件夹中获取文件,帮助我从手机中获取文件,

The file from Assets folder opening properly but I want it to be select from my phone 来自Assets文件夹的文件可以正常打开,但是我希望从手机中选择该文件

You can get file path in onActivityResult which you selected from file manager. 您可以从文件管理器中选择的onActivityResult获取文件路径。

 Uri PathHolder = data.getData();

UPDATE 更新

Above line give you uri of file which you selected from storage. 上面的行为您提供从存储中选择的文件的uri Then You can get File from that Uri easily. 然后,您可以轻松地从该Uri获取文件。

Just forgot about getAssets Use Following method to read from 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();
    }

}

You can try this approach: 您可以尝试以下方法:

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

and for the intent: 并出于以下目的:

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

    } 

There is a slight change in your onActivityResult First paste this code in your activity. 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());
    }

now change your onActivityResult to this. 现在将您的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();
                }



            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM