我在模拟器中的SD卡上写文件时遇到问题。这是我的代码:
File directory;
directory = new File("/sdcard/b/b");
directory.mkdirs();
...
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
serializer.setOutput(writer);
...
String fileName = new Date().toString();
FileOutputStream fOut = healthCareApplication.openFileOutput("/sdcard/b/b"+fileName+".xml",Context.MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(writer.toString());
osw.flush();
osw.close();
首先我在SD卡上创建目录,然后我构建一些XML文件。然后我尝试创建一个文件,并尝试将此XML文件保存到此目录,但我得到IllegalArgumentException并且应用程序崩溃。 “healthCareApplication”是扩展应用程序类的类。这段代码有什么问题?
修改
好的,我添加了“Environment.getExternalStorageDirectory()。getAbsolutePath();”这是我在Logcat中得到的:
08-13 16:29:34.168: ERROR/AndroidRuntime(419): FATAL EXCEPTION: pool-1-thread-5
08-13 16:29:34.168: ERROR/AndroidRuntime(419): java.lang.IllegalArgumentException: File /mnt/sdcard/c/c/Sat Aug 13 16:29:34 GMT+00:00 2011.xml contains a path separator
08-13 16:29:34.168: ERROR/AndroidRuntime(419): at android.app.ContextImpl.makeFilename(ContextImpl.java:1648)
08-13 16:29:34.168: ERROR/AndroidRuntime(419): at android.app.ContextImpl.openFileOutput(ContextImpl.java:414)
08-13 16:29:34.168: ERROR/AndroidRuntime(419): at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:158)
08-13 16:29:34.168: ERROR/AndroidRuntime(419): at com.myapp.runnable.ServerWorker.packageToXML(ServerWorker.java:197)
08-13 16:29:34.168: ERROR/AndroidRuntime(419): at com.myapp.runnable.ServerWorker.run(ServerWorker.java:85)
08-13 16:29:34.168: ERROR/AndroidRuntime(419): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
08-13 16:29:34.168: ERROR/AndroidRuntime(419): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
08-13 16:29:34.168: ERROR/AndroidRuntime(419): at java.lang.Thread.run(Thread.java:1019)
当我检查DDMS时,我发现该文件夹是在sdcard中创建的,但是在该目录中没有任何可能,当应用程序尝试将文件写入SD卡时,可能会出现问题。
我也替换
"FileOutputStream fOut = healthCareApplication.openFileOutput("/sdcard/b/b"+fileName+".xml",Context.MODE_WORLD_READABLE);"
代表
File outputFile = new File(wallpaperDirectory, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
并获得另一个例外:
08-13 16:46:56.108: INFO/IOException(3110): /Sat Aug 13 16:46:56 GMT+00:00 2011 (Read-only file system)
答案 0 :(得分:1)
生成第一个异常是因为使用new Date().toString();
生成的文件名包含冒号(:)。这在文件名中是非法的。
第二个异常看起来像wallpaperDirectory是空白的,因为你正在尝试写入/目录(只读),因此正在生成异常。