[英]File.createTempFile (Error: java.io.IOException: No such file or directory)
code with debug app In my app I would like to create a file but I get the error No such file or directory in the Android Studio emulator. 使用调试应用程序编写代码在我的应用程序中,我想创建一个文件,但是出现错误,Android Studio模拟器中没有这样的文件或目录。 I added the Manifest.permission.CAMERA
, Manifest.permission.WRITE_EXTERNAL_STORAGE
and Manifest.permission.READ_EXTERNAL_STORAGE
as you can see in the code. 我在代码中添加了Manifest.permission.CAMERA
, Manifest.permission.WRITE_EXTERNAL_STORAGE
和Manifest.permission.READ_EXTERNAL_STORAGE
。 But when I do this on my own phone this is working and creating the image. 但是,当我在自己的手机上执行此操作时,就可以创建图像。 Anyone know this issue? 有人知道这个问题吗?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_input_screen);
takePhoto = findViewById(R.id.add_photoWarranty);
cancelInput = findViewById(R.id.cancel_input);
//check camera permission
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE }, 100);
}
//Cancel button
cancelInput.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
//take picture button
takePhoto.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
// Create an image file name
String imageFileName = "JPEG_timeStamp_";
File dir = new File(Environment.getExternalStorageDirectory() + "/MyWarranty");
if(!dir.isDirectory()) {
dir.mkdir();
}
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
dir // directory
);
photoFile = image;
} catch (IOException ex) {
// Error occurred while creating the File
Log.i("Error", ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
});
}
}
Problem is here: 问题在这里:
if(!dir.isDirectory()) {
dir.mkdir();
}
dir
is a directory, and so dir.mkdir()
is never called, and so the directory is never created. dir
是一个目录,因此从不调用dir.mkdir()
,因此从不创建该目录。
Remove this if
condition, it's not even necessary, since it's a hardcoded value and you know it's a directory. if
有条件则将其删除,因为它是一个硬编码的值,并且您知道它是一个目录,所以甚至没有必要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.