我需要完成这些步骤:
- 让用户选择一个文件(任何类型的文件)
- 获取永久引用以便稍后访问文件或复制到我的内部存储。
第一个真的很简单。使用 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/