How to create/write file in the root of the Android device?
Solution 1
Context.openFileOutput is meant to be used for creating files private to your application. they go in your app's private data directory. you supply a name, not a path: "name The name of the file to open; can not contain path separators".
http://developer.android.com/reference/android/content/Context.html#openFileOutput(java.lang.String, int)
as for your question, you can't write to / unless you're root:
my-linux-box$ adb shell ls -l -d / drwxr-xr-x root root 2010-01-16 07:42 $
i don't know what your API is that expects you to write to the root directory, but i'm guessing it's not an Android API and you're reading the wrong documentation ;-)
Solution 2
You can add files with path in private directory like that
String path = this.getApplicationContext().getFilesDir() + "/testDir/";
File file = new File(path);
file.mkdirs();
path += "testlab.txt";
OutputStream myOutput;
try {
myOutput = new BufferedOutputStream(new FileOutputStream(path,true));
write(myOutput, new String("TEST").getBytes());
myOutput.flush();
myOutput.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Ted
Been programming since around the year 2000 where I started out with C# and PHP for different projects, and since quickly learned to love .NET and C#, which has grown from good to GREAT. Have dabbled with JAVA, Java for Android, PHP, JS, CSS, HTML, but C# is my thing.
Updated on February 03, 2020Comments
-
Ted over 4 years
I found out that you can use something like this to create a file:
FileOutputStream fs = openFileOutput("/test.in", MODE_WORLD_WRITEABLE); String s = "[Head]\r\n"; s += "Type=2"; byte[] buffer = s.getBytes(); fs.write(buffer); fs.close();
When running the above code I get an IllegalArgumentException stating:
java.lang.IllegalArgumentException: File /test.in contains a path separator
and I'm guessing the "/" is not appreciated. I wanted the "/" since I need to write the file to the root directory of the device, as stated in the API in trying to follow:
A request is a textfile (UNICODE) with the file extension ".in". The application reads and parses the .in file when it's placed in root directory on the mobile device.
Question is: how do I place a file in the root-directory? I have been looking around for an answer, but haven't found one yet.