Skip to content Skip to sidebar Skip to footer

Android Files In Intenal Storage And Local Directory

Android gives you getDir (I assume this means I would have myappspace/somedirectory) to create a directory in you application space. But how do you read or write to a file in that

Solution 1:

getDir returns a File object. To manipulate the directory and file structure, you continue to use File objects. For example

Filedir= getDir("myDir", Context.MODE_PRIVATE);
FilemyFile=newFile(dir, "myFile");

the openFileOutput simply returns a FileOutputStream based on some text criteria. All we have to do is create the object

FileOutputStream out = new FileOutputStream(myFile);

From here, you continue as normal.

String hello = "hello world";
out.write(hello.getBytes());
out.close();

FileInputStream would follow the same guidelines.

Solution 2:

The point is that openFileInput() and openFileOutput() work with files in that directory directly so they don't need an absolute pathname.

EDIT: More accurately, they work with files in the directory returned by getFilesDir() rather than getDir() which is normally the package root.

If you want to create custom directories relative to getDir(), then you'll need to use classes/methods other than openFileInput() and openFileOutput() (such as using InputStream and OutputStream and relevant file 'reader' / 'writer' classes).

Post a Comment for "Android Files In Intenal Storage And Local Directory"