我发现你可以用类似的方法创建一个文件:
FileOutputStream fs = openFileOutput("/test.in", MODE_WORLD_WRITEABLE);
String s ="[Head]
";
s +="Type=2";
byte[] buffer = s.getBytes();
fs.write(buffer);
fs.close();
运行上述代码时,我得到一个IllegalArgumentException,声明:
java.lang.IllegalArgumentException:
File /test.in contains a path
separator
我猜"/"是不受欢迎的。我想要"/",因为我需要将文件写入设备的根目录,正如API在尝试执行以下操作时所述:
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.
问题是:如何在根目录中放置文件?我一直在四处寻找答案,但还没有找到。
参见anddev.org/working_with_files-t115.html
作为第三方应用程序开发人员,不能在根目录period中放置文件。
context.openfileoutput用于创建应用程序专用的文件。它们会进入你应用程序的私有数据目录。您提供一个名称,而不是路径:"名称要打开的文件的名称;不能包含路径分隔符"。
http://developer.android.com/reference/android/content/context.html_openfileoutput(java.lang.string,int)
至于你的问题,你不能写信给/除非你是根:
我的Linux盒$adb shell ls-l-d/drwxr-xr-x根2010-01-16 07:42$
我不知道你的api是什么,它希望你写入根目录,但我猜它不是android api,你读错了文档;-)
谢谢你的回答。它是唯一可以与此应用程序"通信"的API。通过在根目录中创建文本文件进行通信,如上文所述。所以这不是错误的文档——它是唯一存在的文档。我会与他们联系,询问他们对Android的期望是如何实现的=)
您确定不需要写入SD卡的根目录吗?
您可以像这样在私有目录中添加具有路径的文件
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();
}
"write(outputstream,byte[])"在哪里声明?我不得不使用myoutput.write(byte[])来让它工作。
我今天也面临同样的问题
java.lang.illegalargumentexception:file/test.txt包含路径分隔符
当我尝试以下方法时,它起作用了。
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
}
}
(顺便说一句,我在/root目录外发现这个问题,在搜索时看到了这个帖子)
答案是thx。如果我再次参与到Android开发中,我会尝试一下的=)