以下代码输出是“Write written”但在此之后错误'/ storage_emulated/0/Download/test.txt:open failed:EACCES(Permission denied)'
怎么了?
@RunWith(AndroidJUnit4.class)
public class FileStorageTest {
private static final String TAG = FileStorageTest.class.getSimpleName();
@Test
public void test() throws Exception {
Context context = InstrumentationRegistry.getTargetContext();
if (context.checkSelfPermission("android.permission.WRITE_EXTERNAL_STORAGE") == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Write granted");
} else {
Log.e(TAG, "Write refused");
}
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"test.txt");
new FileOutputStream(file).close();
}
}
答案 0 :(得分:1)
您还需要添加
READ_EXTERNAL_STORAGE
权限才能从设备读取数据。也在
RunTime
添加此权限。
if (context.checkSelfPermission("android.permission.READ_EXTERNAL_STORAGE") == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Read granted");
} else {
Log.e(TAG, "Read refused");
}
答案 1 :(得分:0)
尝试将此添加到您的清单文件中:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />