Issue creating a file in android

10,746

Solution 1

Try this,

File new_file =new File(directory.getAbsolutePath() + File.separator +  "new_file.png");
try
  {
   new_file.createNewFile();
  }
  catch (IOException e)
  {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
Log.d("Create File", "File exists?"+new_file.exists());

But be sure,

public boolean createNewFile () 

Creates a new, empty file on the file system according to the path information stored in this file. This method returns true if it creates a file, false if the file already existed. Note that it returns false even if the file is not a file (because it's a directory, say).

Solution 2

Creating a File instance doesn't necessarily mean that file exists. You have to write something into the file to create it physically.

File directory = ...
File file = new File(directory, "new_file.png");
Log.d("Create File", "File exists? " + file.exists());  // false

byte[] content = ...
FileOutputStream out = null;
try {
    out = new FileOutputStream(file);
    out.write(content);
    out.flush();  // will create the file physically.
} catch (IOException e) {
    Log.w("Create File", "Failed to write into " + file.getName());
} finally {
    if (out != null) {
        try {
            out.close();
        } catch (IOException e) {
        }
    }
}

Or, if you want to create an empty file, you could just call

file.createNewFile();
Share:
10,746
user264953
Author by

user264953

Updated on June 19, 2022

Comments

  • user264953
    user264953 almost 2 years

    I am trying to create a file inside a directory using the following code:

    ContextWrapper cw = new ContextWrapper(getApplicationContext());
        File directory = cw.getDir("themes", Context.MODE_WORLD_WRITEABLE);
        Log.d("Create File", "Directory path"+directory.getAbsolutePath());
        File new_file =new File(directory.getAbsolutePath() + File.separator +  "new_file.png");
        Log.d("Create File", "File exists?"+new_file.exists());
    

    When I check the file system of emulator from eclipse DDMS, I can see a directory "app_themes" created. But inside that I cannot see the "new_file.png" . Log says that new_file does not exist. Can someone please let me know what the issue is?

    Regards, Anees