Android No such file or directory exception
I’m trying to follow this tutorial https://developer.android.com/training/camera/photobasics.html#TaskPath for taking an image and saving the file. It opens the camera, I take a picture, click the check mark, then it crashes. I have found several articles on StackOverflow and have tried all of their solutions that I could understand (which were file.mkdirs() , file.getParentFile().mkdirs() ). It seems that, even though it’s a RuntimeException, the root problem is the IOException (which I catch and print the message). I’m using Genymotion, not sure if that’s relevant or not. What have I missed that is keeping me from being able to create the file? I have added permissions to my manifest:
public void onClick(View v) < Log.d("DebugMySocks", "Change photo button clicked"); Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); try < // CHANGED THIS mImageUri = FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + "socks", createImageFile()); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri); >catch (Exception e) < Log.d("DebugMySocks", "Error creating file " + e.getMessage()); >if (takePictureIntent.resolveActivity(getPackageManager()) != null) < startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); >>
private File createImageFile() throws IOException < //ADDED THIS int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (permissionCheck != PackageManager.PERMISSION_GRANTED) < ActivityCompat.requestPermissions(this, new String[], 5); > // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; File storageDir = Environment.getExternalStorageDirectory(); Log.d("DebugMySocks", "Storage directory is: " + storageDir); File image = new File(Environment.getExternalStorageDirectory() + File.separator + "socks"+ File.separator + imageFileName); Log.d("DebugMySocks", "getAbsoluteFile: " + image.getAbsoluteFile()); image.getParentFile().mkdirs(); image.mkdirs(); image.createNewFile(); //File image = File.createTempFile( // imageFileName, /* prefix */ // ".jpg", /* suffix */ // storageDir /* directory */ //); // Save a file: path for use with ACTION_VIEW intents mCurrentPhotoPath = image.getAbsolutePath(); return image; >
12-14 08:05:01.411 4967-4967/com.example.kevin.moresocksplease D/DebugMySocks: Change photo button clicked 12-14 08:05:01.412 4967-4967/com.example.kevin.moresocksplease D/DebugMySocks: Storage directory is: /storage/emulated/0 12-14 08:05:01.413 4967-4967/com.example.kevin.moresocksplease D/DebugMySocks: getAbsoluteFile: /storage/emulated/0/socks/JPEG_20171214_080501_ 12-14 08:05:01.416 4967-4967/com.example.kevin.moresocksplease D/DebugMySocks: Error creating file No such file or directory
FATAL EXCEPTION: main Process: com.example.kevin.moresocksplease, PID: 4967 java.lang.RuntimeException: Failure delivering result ResultInfo> to activity : java.lang.NullPointerException: uri at android.app.ActivityThread.deliverResults(ActivityThread.java:4089) at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132) at android.app.ActivityThread.-wrap20(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6119) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) Caused by: java.lang.NullPointerException: uri at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:111) at android.content.ContentResolver.notifyChange(ContentResolver.java:1714) at android.content.ContentResolver.notifyChange(ContentResolver.java:1693) at com.example.kevin.moresocksplease.EditProfileActivity.onActivityResult(EditProfileActivity.java:254) at android.app.Activity.dispatchActivityResult(Activity.java:6932) at android.app.ActivityThread.deliverResults(ActivityThread.java:4085) at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132) at android.app.ActivityThread.-wrap20(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6119) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
public void onActivityResult(int requestCode, int resultCode, Intent data) < Log.d("DebugMySocks", "onActivityResult in EditProfileActivity"); if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == this.RESULT_OK) < this.getContentResolver().notifyChange(mImageUri, null); // catch (Exception e) < Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show(); Log.d("DebugMySocks", "Failed to load", e); >> >
Additional links that I’ve been drawing information from: File.createNewFile() thowing IOException No such file or directory Android Camera Intent: how to get full sized photo? Edit 1: After viewing this, I added logs to the mkdir requests and they both return false. According to this gentleman, that means the directories already exist, so it’s just the creation of the file that is failing? Creating a directory in /sdcard fails
Log.d("DebugMySocks", "parentfile mkdirs: " + image.getParentFile().mkdirs()); Log.d("DebugMySocks", "image.mkdirs: " + image.mkdirs()); Log.d("DebugMySocks", "create file: " + image.createNewFile()); DebugMySocks: parentfile mkdirs: false DebugMySocks: image.mkdirs: false DebugMySocks: Error creating file No such file or directory
public void onClick(View v) < Log.d("DebugMySocks", "Change photo button clicked"); Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); try < if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED) < mImageUri = FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + "socks", createImageFile()); >else < Log.v("DebugMySocks","Permission is revoked"); ActivityCompat.requestPermissions(getParent(), new String[], 1); > takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri); > catch (Exception e) < Log.d("DebugMySocks", "Error creating file " + e.getMessage()); >if (takePictureIntent.resolveActivity(getPackageManager()) != null) < startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); >> public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) < switch (requestCode) < case 0: boolean permissionsGranted = true; if (grantResults.length >0 && permissions.length==grantResults.length) < for (int i = 0; i < permissions.length; i++)< if (grantResults[i] != PackageManager.PERMISSION_GRANTED)< permissionsGranted=false; >> > else < permissionsGranted=false; >if(permissionsGranted) < try < mImageUri = FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + "socks", createImageFile()); >catch (Exception e) < Log.d("DebugMySocks", "Permissions granted but exception happened " + e.getMessage()); >> break; > >
But I get Error creating file Attempt to invoke virtual method ‘android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)’ on a null object reference
Java create new file
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Creating a file is a very common IO operation. Today we will look into different ways to create a file in java.
Java create file
There are three popular methods to create file in java. Let’s look at them one by one.
File.createNewFile()
java.io.File class can be used to create a new File in Java. When we initialize File object, we provide the file name and then we can call createNewFile() method to create new file in Java. File createNewFile() method returns true if new file is created and false if file already exists. This method also throws java.io.IOException when it’s not able to create the file. The files created is empty and of zero bytes. When we create the File object by passing the file name, it can be with absolute path, or we can only provide the file name or we can provide the relative path. For a non-absolute path, File object tries to locate files in the project root directory. If we run the program from command line, for the non-absolute path, File object tries to locate files from the current directory. While creating the file path, we should use System property file.separator to make our program platform independent. Let’s see different scenarios with a simple java program to create a new file in java.
package com.journaldev.files; import java.io.File; import java.io.IOException; public class CreateNewFile < /** * This class shows how to create a File in Java * @param args * @throws IOException */ public static void main(String[] args) throws IOException < String fileSeparator = System.getProperty("file.separator"); //absolute file name with path String absoluteFilePath = fileSeparator+"Users"+fileSeparator+"pankaj"+fileSeparator+"file.txt"; File file = new File(absoluteFilePath); if(file.createNewFile())< System.out.println(absoluteFilePath+" File Created"); >else System.out.println("File "+absoluteFilePath+" already exists"); //file name only file = new File("file.txt"); if(file.createNewFile())< System.out.println("file.txt File Created in Project root directory"); >else System.out.println("File file.txt already exists in the project root directory"); //relative path String relativePath = "tmp"+fileSeparator+"file.txt"; file = new File(relativePath); if(file.createNewFile())< System.out.println(relativePath+" File Created in Project root directory"); >else System.out.println("File "+relativePath+" already exists in the project root directory"); > >
/Users/pankaj/file.txt File Created file.txt File Created in Project root directory Exception in thread "main" java.io.IOException: No such file or directory at java.io.UnixFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(File.java:947) at com.journaldev.files.CreateNewFile.main(CreateNewFile.java:32)
For the relative path, it throws IOException because tmp directory is not present in the project root folder. So it’s clear that createNewFile() just tries to create the file and any directory either absolute or relative should be present already, else it throws IOException . So I created “tmp” directory in the project root and executed the program again, here is the output.
File /Users/pankaj/file.txt already exists File file.txt already exists in the project root directory tmp/file.txt File Created in Project root directory
First two files were already present, so createNewFile() returns false , third file was created in tmp directory and returns true. Any subsequent execution results in the following output:
File /Users/pankaj/file.txt already exists File file.txt already exists in the project root directory File tmp/file.txt already exists in the project root directory
//first execution from classes output directory pankaj:~/CODE/JavaFiles/bin$ java com/journaldev/files/CreateNewFile File /Users/pankaj/file.txt already exists file.txt File Created in Project root directory Exception in thread "main" java.io.IOException: No such file or directory at java.io.UnixFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(File.java:947) at com.journaldev.files.CreateNewFile.main(CreateNewFile.java:32) //tmp directory doesn't exist, let's create it pankaj:~/CODE/JavaFiles/bin$ mkdir tmp //second time execution pankaj:~/CODE/JavaFiles/bin$ java com/journaldev/files/CreateNewFile File /Users/pankaj/file.txt already exists File file.txt already exists in the project root directory tmp/file.txt File Created in Project root directory //third and subsequent execution pankaj:~/CODE/JavaFiles/bin$ java com/journaldev/files/CreateNewFile File /Users/pankaj/file.txt already exists File file.txt already exists in project root directory File tmp/file.txt already exists in project root directory
FileOutputStream.write(byte[] b)
If you want to create a new file and at the same time write some data into it, you can use FileOutputStream write method. Below is a simple code snippet to show it’s usage. The rules for absolute path and relative path discussed above is applicable in this case too.
String fileData = "Pankaj Kumar"; FileOutputStream fos = new FileOutputStream("name.txt"); fos.write(fileData.getBytes()); fos.flush(); fos.close();
Java NIO Files.write()
We can use Java NIO Files class to create a new file and write some data into it. This is a good option because we don’t have to worry about closing IO resources.
String fileData = "Pankaj Kumar"; Files.write(Paths.get("name.txt"), fileData.getBytes());
That’s all for creating a new file in the java program.
You can checkout more core java examples from our GitHub Repository.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
open failed: ENOENT (No such file or directory) internal storage
I have a little bit of trouble finding my error in my Android application. The target of my «ResultActivity» is, to create a file in the internal storage and then download a file from my server (via FTP) and then call the next Activity (GiftActivity). But when the next Activity tries to access these files, I get the mentioned error. As far nothing new, but the interesting part is, that if I kill the application by hand and restart it, it works like a charm the next time. Here’s my code: ResultActivity.java:
//. ImageButton download = (ImageButton) findViewById(R.id.downloadCode); download.setBackgroundDrawable(null); assert download != null; download.setOnClickListener(new View.OnClickListener() () File code = new File(getFilesDir().getAbsolutePath(), "code.txt"); File usage = new File(getFilesDir().getAbsolutePath(), "usage.txt"); code.createNewFile(); usage.createNewFile(); channelSftp.get("/home/code.txt", getFilesDir() + "/code.txt"); channelSftp.get("/home/usage.txt", getFilesDir() + "/usage.txt"); > catch (JSchException e) < e.printStackTrace(); >catch (SftpException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >return null; > >.execute(1); Intent intent = new Intent(ResultActivity.this, GiftActivity.class); ResultActivity.this.startActivity(intent); ResultActivity.this.finish(); > >);
protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_gift); TextView actualCode = (TextView) findViewById(R.id.actualCode); TextView actualUsage = (TextView) findViewById(R.id.usageCode); String code = ""; String usage = ""; try < FileInputStream fis = getBaseContext().openFileInput("code.txt"); InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) < sb.append(line).append("\n"); >code = sb.toString(); > catch (IOException e) < e.printStackTrace(); code="error1"; >try < FileInputStream fis = getBaseContext().openFileInput("usage.txt"); InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) < sb.append(line).append("\n"); >usage = sb.toString(); > catch (IOException e) < e.printStackTrace(); usage="error2"; >actualCode.setText(code); actualUsage.setText("you got a gift for " + usage + " congratulation!"); >