2011-08-13 49 views
0

我在模拟器中的SD卡上写入文件时出现问题。这里是我的代码:将文件保存在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”是扩展应用程序类的类。这段代码有什么问题?

EDIT

好的,我添加 “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我看到文件夹在SD卡创建的,但在该目录中没有这样可能当应用程序试图写文件到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) 
+4

只是一个普遍的建议:*从不*硬编码的存储路径,如SD卡。使用'Environment.getExternalStorageDirectory()'。有些设备没有SD卡,只能依靠内置闪存或将其完全安装到其他位置。 – 2011-08-13 13:43:40

+1

此外,'/ sdcard'对于目前使用的大多数Android设备来说只是错误的。使用'Environment.getExternalStorageDirectory()',并确保具有'WRITE_EXTERNAL_STORAGE'权限。如果这没有帮助,请使用Eclipse中的'adb logcat',DDMS或DDMS透视图来检查LogCat并查看崩溃发生的位置。 – CommonsWare

+0

发布完整的LogCat输出。 –

回答

1

产生第一个例外,因为new Date().toString();正在生成的文件名包含冒号( :)。这在文件名中是非法的。

它看起来像wallpaperDirectory的第二个异常是空白的,因为正在生成异常,因为您正在尝试写入/目录(这是只读)。