android - 获取并保存使用 Intent.ACTION_GET_CONTENT 选择的任何文件

标签 android android-intent io android-fileprovider

我需要完成这些步骤:

  1. 让用户选择一个文件(任何类型的文件)
  2. 获取永久引用以便稍后访问文件或复制到我的内部存储。

第一个真的很简单。使用 Intent.ACTION_GET_CONTENT 获取文件没有任何问题。我也可以获得文件的 MimeType。但是我不能复制。

我尝试使用 FileInputStream 进行复制,但显然我没有权限。我真的希望有人能帮助我。

权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />

Intent 调用

    Intent intent   = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    if ( intent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(intent, REQUEST_FILE_GET);
    }

尝试复制文件失败

 FileInputStream in = (FileInputStream) getContentResolver().openInputStream( data.getData());
 FileOutputStream out = new FileOutputStream( "copy.jpg ");
 FileChannel inChannel   = in.getChannel();
 FileChannel outChannel  = out.getChannel();
 inChannel.transferTo(0, inChannel.size(), outChannel);
 in.close();
 out.close();

错误:android.system.ErrnoException:打开失败:EROFS(只读文件系统)

最佳答案

您正在尝试在根目录 /copy.jpg 中创建输出流文件,该文件是只读的。

使用 Environment 之一方法,例如 getExternalStorageDirectory(),或 Context 之一getFilesDir() 等方法,用于构建您具有写入权限的目录的路径。

例如:

File outFile = new File(Environment.getExternalStorageDirectory(), "copy.jpg");
FileOutputStream out = new FileOutputStream(outFile);

documentation描述了在内部或外部存储中存储文件的不同选项。

关于android - 获取并保存使用 Intent.ACTION_GET_CONTENT 选择的任何文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31085825/

相关文章:

android - 在 android 中创建拼贴 ImageView 库

android - 在拨号盘上按数字启动 Activity

android - 如何在 Android 中终止 PostDelayed 方法

安卓.content.ActivityNotFoundException : Unable to find explicit activity class - Intent in a Fragment

c++ - Linux I/O 管理器

android - BackupManager 不调用备份传输

java - MediaPlayer 出现错误

java - 应用程序存储设置的 Intent

io - C printf 打印的文本在哪里

Java 8 的 Files.lines() : Performance concern for very long line