[英]android writing to sdcard
我无法写SDCARD。 我无法创建目录或文件,清单中缺少此内容
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
这在我的代码中
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 ("<?xml version=\"1.0\"?>");
out.write ("<?mso-application progid=\"Excel.Sheet\"?>");
out.write ("Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"");
out.close();
} // end try
catch (IOException e)
{
} // end catch
} // end public
}); // end SAVE Button
第一件事:
只需检查“成功”变量,是否返回true即可 。
第二件事:
由于已经对/ sdcard进行了硬编码,因此我建议您使用以下目录来获取目录: Environment.getExternalStorageDirectory()
因为在某些设备中sd卡的根目录是/ 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
构造函数,如果文件不存在,则创建该文件,但不包括目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.