File.createTempFile(错误:java.io.IOException:没有这样的文件或目录)

时间:2017-12-19 16:59:39

标签: java android

code with debug app在我的应用中,我想创建一个文件但是我在Android Studio模拟器中收到错误没有这样的文件或目录。我在代码中添加了Manifest.permission.CAMERAManifest.permission.WRITE_EXTERNAL_STORAGEManifest.permission.READ_EXTERNAL_STORAGE。但是,当我在自己的手机上执行此操作时,这可以正常工作并创建图像。有人知道这个问题吗?

@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);
            }
        }
    }

});
}


}

1 个答案:

答案 0 :(得分:0)

问题出在这里:

if(!dir.isDirectory()) {
    dir.mkdir();
}

dir是一个目录,因此永远不会调用dir.mkdir(),因此永远不会创建目录。

删除此if条件,它甚至不是必需的,因为它是一个硬编码值,你知道它是一个目录。