我正在尝试从我的testcase写一个文件。我正在尝试写入内部存储,但它给出了权限错误。 `
Context context = InstrumentationRegistry.getContext();
AssetManager assetManager = context.getAssets();
InputStream inputStream = null;
try {
inputStream = context.getAssets().open("myFile");
} catch (IOException e) {
e.printStackTrace();
}
try{
File f = new File(context.getFilesDir(),"outfile");
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
e.printStackTrace();
}
return null;
}`
java.io.FileNotFoundException:/ data / user / 0 / package / files / outfile(Permission denied)
答案 0 :(得分:0)
您可以使用Junit的临时文件夹来模拟本地存储。
TemporaryFolder temporaryFolder = getTemporaryFolder();
File outFile = temporaryFolder.newFile("outFile");
OutputStream outputStream = new FileOutputStream(outFile);
答案 1 :(得分:0)
问题在于背景。用于获取app上下文而不是context = InstrumentationRegistry.getContext();使用getTargetContext(()