arinte
arinte

Reputation: 3728

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 directory when android gives you an error if you have the path separator in the openFileOutput/Input call it gives you an error?

Upvotes: 3

Views: 10875

Answers (2)

Squonk
Squonk

Reputation: 48871

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

Upvotes: 4

Daniel Skinner
Daniel Skinner

Reputation: 220

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

File dir = getDir("myDir", Context.MODE_PRIVATE);
File myFile = new File(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.

Upvotes: 6

Related Questions