FAZ
FAZ

Reputation: 285

Android creating a file in /data/local/ and writng into it

I am using a non-activity class and I want to create a file in /data/local/ path. I am using Emulator for this. Once the file is created in this path, I want to write some String in the file for every 10 seconds.

Since I am using non-Activity class, I have no context working for me and I want to do without using context.

Could any one please help me how i could achieve this? Thanks in advance :)

My code is -

try {
                File myFile = new File("/data/local/tmp/welcome-to-java.txt");
                myFile.createNewFile();
                FileOutputStream fOut = new FileOutputStream(myFile);
                OutputStreamWriter myOutWriter = 
                                        new OutputStreamWriter(fOut);
                myOutWriter.append(tempList.toString());
                myOutWriter.close();
                fOut.close();

            } catch (Exception e) {

            }

Upvotes: 2

Views: 2582

Answers (2)

Kelevandos
Kelevandos

Reputation: 7082

You need a Context instance to access the file system :-) However, it is virtually impossible that you have "no context working for you", as every Object in Android runtime will actually be created in some Context (Activity, Service, BroadcastReceiver etc.), so just pass that Context into the Object :-)

And as for how to do it with Context, just use

yourContext.openFileOutput(path, Context.MODE_PRIVATE);

To obtain a FileOutputStream you need :-)


EDIT:

There is one way to avoid passing Context directly, but be warned that it is generally frowned upon. Namely, creating a custom Application class and making it a Singleton. This will allow you to access your Context from any place, but can also lead to severe memory leaks if, for example, you try using it in a long-running worker Thread. So use it wisely, if you really have to use it at all ;-)

Just to put it into perspective - first iterations of Android system actually provided static Context by default. I have also worked with a few current-time, commercial apps that use Application Singleton with no problems. So it is not that crazy of an idea. Nevertheless, it requires a huge dose of self-discipline to work out correctly.

Upvotes: 2

CommonsWare
CommonsWare

Reputation: 1006624

I am using a non-activity class and I want to create a file in /data/local/ path.

There is no /data/local/ directory on production hardware that you can access sans root.

There is /data/local/tmp/ that does seem to be world-readable and world-writeable. I would not recommend using it, as it is wide open for all parties, including attackers.

Could any one please help me how i could achieve this?

Use Java file I/O, starting with new File("/data/local/tmp/welcome-to-java.txt").

Upvotes: 5

Related Questions