Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue creating a file in android

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

like image 688
user264953 Avatar asked Mar 14 '12 06:03

user264953


2 Answers

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).

like image 166
user370305 Avatar answered Nov 02 '22 12:11

user370305


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();
like image 4
jabu.10245 Avatar answered Nov 02 '22 11:11

jabu.10245