我不断收到错误 每次我在模拟器中运行代码时,它都会显示创建目录的“Toast”,但在该行代码后不久就会出现错误。出现的错误是:
“/ storage / sdcard / Pictures / screenshot.png:打开失败:ENOENT(没有这样的文件或目录)”
我在下面放了相关代码。
<manifest
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="19"
/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18"
/>
</manifest>
public class myActivity {
private void openScreenPrint() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)){
View v1 = findViewById(R.id.myRelativeLayout).getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap myBM = Bitmap.createBitmap(v1.getDrawingCache());
saveBitmap(myBM);
v1.setDrawingCacheEnabled(false);
}
else{
Toast.makeText(this, "No Permission to Write", Toast.LENGTH_SHORT).show();
}
}
public void saveBitmap(Bitmap bitmap) {
FileOutputStream fos = null;
String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File dir = new File(filePath);
if (!dir.exists()){
dir.mkdirs();
Toast.makeText(this, "created", Toast.LENGTH_LONG).show(); //This line shown every time
}
String fileName = "screenshot" + ".png";
File imagePath = new File(filePath, fileName);
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
//Log.e("Err", e.getMessage(), e);
} catch (IOException e) {
//Log.e("Err", e.getMessage(), e);
}
}
}
答案 0 :(得分:0)
您是否在AVD中创建了SD卡?如果没有,这是您在创建/编辑模拟设备时要使用的条目:
答案 1 :(得分:0)
您实际上并不知道该目录实际上是在创建。无论目录创建成功与否,您都在制作Toast。您应该更改此部分:
if (!dir.exists()){
dir.mkdirs();
Toast.makeText(this, "created", Toast.LENGTH_LONG).show();
}
测试目录是否实际成功创建。 File.mkdirs()返回一个布尔值。
if (!dir.exists()) {
Toast.makeText(this, "dir not exists. attempting to create...", Toast.LENGTH_SHORT).show();
if (dir.mkdirs()) {
Toast.makeText(this, "dir created", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "dir creation failed", Toast.LENGTH_SHORT).show();
}
}