在Android中实现文件选择器,并将选定的文件复制到另一个位置

前端之家收集整理的这篇文章主要介绍了在Android中实现文件选择器,并将选定的文件复制到另一个位置前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在我的 Android项目中实现文件选择器.我迄今所能做的是:
  1. Intent chooseFile;
  2. Intent intent;
  3. chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
  4. chooseFile.setType("*/*");
  5. intent = Intent.createChooser(chooseFile,"Choose a file");
  6. startActivityForResult(intent,PICKFILE_RESULT_CODE);

然后在我的onActivityResult()

  1. switch(requestCode){
  2. case PICKFILE_RESULT_CODE:
  3. if(resultCode==-1){
  4. Uri uri = data.getData();
  5. String filePath = uri.getPath();
  6. Toast.makeText(getActivity(),filePath,Toast.LENGTH_LONG).show();
  7. }
  8. break;
  9. }

这是打开一个文件选择器,但它不是我想要的.例如,我想选择一个文件(.txt),然后获取文件,然后使用它.有了这个代码,我以为我会得到完整的路径,但不会发生;例如我得到:/ document / 5318 /.但是用这个路径我无法获取文件.我创建了一个名为PathToFile()的方法返回一个文件

  1. private File PathToFile(String path) {
  2. File tempFileToUpload;
  3. tempFileToUpload = new File(path);
  4. return tempFileToUpload;
  5. }

我想要做的是让用户从任何地方选择一个文件,意思是DropBox,Drive,SDCard,Mega等…我没有找到正确的方法,我试图让路径然后得到一个文件由这个路径…但它不工作,所以我认为最好是获取文件本身,然后以该文件编程方式我复制此或删除.

编辑(当前代码)

我的意图

  1. Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
  2. chooseFile.addCategory(Intent.CATEGORY_OPENABLE);
  3. chooseFile.setType("text/plain");
  4. startActivityForResult(
  5. Intent.createChooser(chooseFile,"Choose a file"),PICKFILE_RESULT_CODE
  6. );

在那里我有一个问题,因为我不知道什么是文本/简单的支持,但我会调查它,但这并不重要.

在我的onActivityResult()我使用与@Lukas Knuth answer相同,但我不知道是否可以复制该文件到我的SD卡的另一部分我正在等待他的答案.

  1. @Override
  2. public void onActivityResult(int requestCode,int resultCode,Intent data) {
  3. super.onActivityResult(requestCode,resultCode,data);
  4. if (requestCode == PICKFILE_RESULT_CODE && resultCode == Activity.RESULT_OK){
  5. Uri content_describer = data.getData();
  6. //get the path
  7. Log.d("Path???",content_describer.getPath());
  8. BufferedReader reader = null;
  9. try {
  10. // open the user-picked file for reading:
  11. InputStream in = getActivity().getContentResolver().openInputStream(content_describer);
  12. // now read the content:
  13. reader = new BufferedReader(new InputStreamReader(in));
  14. String line;
  15. StringBuilder builder = new StringBuilder();
  16.  
  17. while ((line = reader.readLine()) != null){
  18. builder.append(line);
  19. }
  20. // Do something with the content in
  21. text.setText(builder.toString());
  22.  
  23.  
  24.  
  25. } catch (FileNotFoundException e) {
  26. e.printStackTrace();
  27. } catch (IOException e) {
  28. e.printStackTrace();
  29. } finally {
  30. if (reader != null) {
  31. try {
  32. reader.close();
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. }
  38. }
  39. }

getPath()from @ Y.S.

我在做这个:

  1. String[] projection = { MediaStore.Files.FileColumns.DATA };
  2. Cursor cursor = getActivity().getContentResolver().query(content_describer,projection,null,null);
  3. int column_index = cursor.getColumnIndexOrThrow(projection[0]);
  4. cursor.moveToFirst();
  5. cursor.close();
  6. Log.d( "PATH-->",cursor.getString(column_index));

得到一个NullPointerException:

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null,request=131073,result=-1,data=Intent { dat=file:///path typ=text/plain flg=0x3 }} to activity {info.androidhive.tabsswipe/info.androidhive.tabsswipe.MainActivity2}: java.lang.NullPointerException

编辑工作感谢@Y.S.,@Lukas Knuth@CommonsWare编辑.

这是我只接受文件/简单的意图.

  1. Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
  2. chooseFile.addCategory(Intent.CATEGORY_OPENABLE);
  3. chooseFile.setType("text/plain");
  4. startActivityForResult(
  5. Intent.createChooser(chooseFile,PICKFILE_RESULT_CODE
  6. );

在我的onActivityResult()我创建一个URI,我获取Intent的数据,我创建一个文件,我保存绝对路径做content_describer.getPath();然后我保留路径的名称在TextView with content_describer.getLastPathSegment(); (这真的很棒@Y.S.不知道那个功能),我创建了一个第二个File,我称之为目标,我发送AbsolutePath可以创建这个文件.

  1. @Override
  2. public void onActivityResult(int requestCode,data);
  3. if (requestCode == PICKFILE_RESULT_CODE && resultCode == Activity.RESULT_OK){
  4. Uri content_describer = data.getData();
  5. String src = content_describer.getPath();
  6. source = new File(src);
  7. Log.d("src is ",source.toString());
  8. String filename = content_describer.getLastPathSegment();
  9. text.setText(filename);
  10. Log.d("FileName is ",filename);
  11. destination = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Test/TestTest/" + filename);
  12. Log.d("Destination is ",destination.toString());
  13. SetToFolder.setEnabled(true);
  14. }
  15. }

此外,我创建了一个函数,您必须发送源文件和我们之前创建的目标文件将其复制到新文件夹.

  1. private void copy(File source,File destination) throws IOException {
  2.  
  3. FileChannel in = new FileInputStream(source).getChannel();
  4. FileChannel out = new FileOutputStream(destination).getChannel();
  5.  
  6. try {
  7. in.transferTo(0,in.size(),out);
  8. } catch(Exception e){
  9. Log.d("Exception",e.toString());
  10. } finally {
  11. if (in != null)
  12. in.close();
  13. if (out != null)
  14. out.close();
  15. }
  16. }

此外,对我说如果这个文件夹存在或不存在(我必须发送目标文件,如果它不存在我创建这个文件夹,如果我不做任何事情.

  1. private void DirectoryExist (File destination) {
  2.  
  3. if(!destination.isDirectory()) {
  4. if(destination.mkdirs()){
  5. Log.d("Carpeta creada","....");
  6. }else{
  7. Log.d("Carpeta no creada","....");
  8. }
  9. }

再次感谢您的帮助,希望您喜欢与大家一起制作的代码:)

解决方法

步骤1 – 使用隐含意图:

要从设备中选择一个文件,你应该使用一个隐含的Intent

  1. Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
  2. chooseFile.setType("*/*");
  3. chooseFile = Intent.createChooser(chooseFile,"Choose a file");
  4. startActivityForResult(chooseFile,PICKFILE_RESULT_CODE);

步骤2 – 获取绝对文件路径:

要从Uri获取文件路径,首先尝试使用

  1. Uri uri = data.getData();
  2. String src = uri.getPath();

其中data是在onActivityResult()中返回的Intent.

如果不行,请使用以下方法

  1. public String getPath(Uri uri) {
  2.  
  3. String path = null;
  4. String[] projection = { MediaStore.Files.FileColumns.DATA };
  5. Cursor cursor = getContentResolver().query(uri,null);
  6.  
  7. if(cursor == null){
  8. path = uri.getPath()
  9. }
  10. else{
  11. cursor.moveToFirst();
  12. int column_index = cursor.getColumnIndexOrThrow(projection[0]);
  13. path = cursor.getString(column_index);
  14. cursor.close();
  15. }
  16.  
  17. return ((path == null || path.isEmpty()) ? (uri.getPath()) : path);
  18. }

这两种方法中至少有一种应该使您获得正确的完整路径.

步骤3 – 复制文件

我想,你想要的是将文件从一个位置复制到另一个位置.

为此,绝对必须具有源和目标位置的绝对文件路径.

首先,使用我的getPath()方法或uri.getPath()获取绝对文件路径:

  1. String src = getPath(uri); /* Method defined above. */

要么

  1. Uri uri = data.getData();
  2. String src = uri.getPath();

然后,创建两个File对象,如下所示:

  1. File source = new File(src);
  2. String filename = uri.getLastPathSegment();
  3. File destination = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/CustomFolder/" + filename);

其中CustomFolder是您要复制文件的外部驱动器上的目录.

然后使用以下方法文件从一个地方复制到另一个地方:

  1. private void copy(File source,File destination) {
  2.  
  3. FileChannel in = new FileInputStream(source).getChannel();
  4. FileChannel out = new FileOutputStream(destination).getChannel();
  5.  
  6. try {
  7. in.transferTo(0,out);
  8. } catch(Exception){
  9. // post to log
  10. } finally {
  11. if (in != null)
  12. in.close();
  13. if (out != null)
  14. out.close();
  15. }
  16. }

尝试这个.这应该工作.

注意:对于Lukas的答案 – 他所做的是使用一个名为openInputStream()的方法来返回Uri的内容,无论Uri是表示文件还是URL.

另一个有希望的方法 – FileProvider:

还有一种方法可以从另一个应用程序获取文件.如果应用程序通过FileProvider共享其文件,那么可以抓住一个保存有关该文件的特定信息的FileDescriptor对象.

为此,请使用以下Intent:

  1. Intent mRequestFileIntent = new Intent(Intent.ACTION_GET_CONTENT);
  2. mRequestFileIntent.setType("*/*");
  3. startActivityForResult(mRequestFileIntent,0);

在你的onActivityResult()中:

  1. @Override
  2. public void onActivityResult(int requestCode,Intent returnIntent) {
  3. // If the selection didn't work
  4. if (resultCode != RESULT_OK) {
  5. // Exit without doing anything else
  6. return;
  7. } else {
  8. // Get the file's content URI from the incoming Intent
  9. Uri returnUri = returnIntent.getData();
  10. /*
  11. * Try to open the file for "read" access using the
  12. * returned URI. If the file isn't found,write to the
  13. * error log and return.
  14. */
  15. try {
  16. /*
  17. * Get the content resolver instance for this context,and use it
  18. * to get a ParcelFileDescriptor for the file.
  19. */
  20. mInputPFD = getContentResolver().openFileDescriptor(returnUri,"r");
  21. } catch (FileNotFoundException e) {
  22. e.printStackTrace();
  23. Log.e("MainActivity","File not found.");
  24. return;
  25. }
  26. // Get a regular file descriptor for the file
  27. FileDescriptor fd = mInputPFD.getFileDescriptor();
  28. ...
  29. }
  30. }

其中mInputPFD是一个ParcelFileDescriptor.

参考文献:

Common Intents – File Storage.

FileChannel.

FileProvider.

4. Requesting a Shared File.

猜你在找的Android相关文章