gpt4 book ai didi

java - 安卓写入sdcard

转载 作者:行者123 更新时间:2023-11-29 08:11:20 25 4
gpt4 key购买 nike

我无法写入 SDCARD。我无法创建目录或文件,我缺少什么我在 list 中有这个

<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

最佳答案

第一件事:

只需检查“success”变量,它是否真的返回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);

关于java - 安卓写入sdcard,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7998185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com