簡體   English   中英

File.createTempFile(錯誤:java.io.IOException:沒有這樣的文件或目錄)

[英]File.createTempFile (Error: java.io.IOException: No such file or directory)

使用調試應用程序編寫代碼在我的應用程序中,我想創建一個文件,但是出現錯誤,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);
            }
        }
    }

});
}


}

問題在這里:

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

dir是一個目錄,因此從不調用dir.mkdir() ,因此從不創建該目錄。

if有條件則將其刪除,因為它是一個硬編碼的值,並且您知道它是一個目錄,所以甚至沒有必要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM