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.
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 ;-)
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();
}
I faced the same problem today
java.lang.IllegalArgumentException: File /test.txt contains a path separator
and when i tried the following it worked.
File inputFile = new File("/storage/new/test.txt");
FileInputStream isr = new FileInputStream(inputFile);
DataInputStream in = new DataInputStream(isr);
if(!inputFile.exists()){
Log.v("FILE","InputFile not available");
}
else
{
while((line = in.readLine()) != null)
{
........ //parse
}
}
(Btw, I was getting this problem outside /root dir and while searching i saw this post)
精彩评论