The problem of 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 emulator file system from eclipse DDMS, I can see the created directory "app_themes". But inside this I do not see "new_file.png". The log says new_file does not exist. Can someone please let me know what the problem is?

Regards, Anise

+4
source share
3 answers

Try it,

 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 rest assured

 public boolean createNewFile () 

Creates a new empty file in the file system in accordance with the path information stored in this file. This method returns true if it creates the file, false if the file already exists. Note that it returns false even if the file is not a file (because it is a directory, say).

+9
source

Creating an instance of File does not necessarily mean that the file exists. You must write something to a file in order 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 can simply call

 file.createNewFile(); 
+4
source

Creating a File object does not mean that a file will be created. You can call new_file.createNewFile() if you want to create an empty file. Or you could write something.

0
source

Source: https://habr.com/ru/post/1401311/


All Articles