android写给sdcard

我无法写入SDCARD。 我无法创建目录或文件,我错过了我在清单中有这个

 

这在我的代码中

 btnSave.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { // Create a directory; all ancestor directories must exist boolean success = (new File("/sdcard/Methods/")).mkdirs(); //create file try{ File myFile = new File("/sdcard/Methods/Method 1 Square.xml"); File file = myFile; // Create file if it does not exist boolean success1 = file.createNewFile();} catch (IOException e) {} //write to file try { BufferedWriter out = new BufferedWriter(new FileWriter("/sdcard/Methods/Method 1 Square.xml")); out.write (""); out.write (""); out.write ("Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\""); out.close(); } // end try catch (IOException e) { } // end catch } // end public }); // end SAVE Button 

第一件事:

只需检查’success’变量,它是否真的返回。

第二件事:

因为你已经对/ sdcard进行了硬编码,所以我建议你使用以下目录获取目录: Environment.getExternalStorageDirectory()因为在某些设备中sd-card根目录是/ mnt / sdcard所以上面的方法来获取根目录。

第三件事:

您应首先检查SD卡是否已安装。

例:

 File sdCard = Environment.getExternalStorageDirectory(); File dir = new File (sdcard.getAbsolutePath() + "/dir/subdir"); // in your case, just give /Methods dir.mkdirs(); File file = new File(dir, "filename"); // in your case, just give "Method 1 Square.xml" FileOutputStream f = new FileOutputStream(file); 

问题可能是路径中的目录不存在。 使用该FileWriter构造函数,如果该文件不存在,则创建该文件,但不包括目录。