6

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

3 Answers 3

18

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

Sign up to request clarification or add additional context in comments.

Comments

4

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(); 

Comments

0

Creating a File object doesn't mean the file will be created. You could call new_file.createNewFile() if you wanted to create an empty file. Or you could write something to it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.