无法写入SD卡 - canWrite是返回falseSD、canWrite、false

2023-09-04 06:47:54 作者:高傲得不顧一屑

对不起,暧昧的称呼,但我做了以下内容写一个简单的字符串到一个文件:

 尝试{
        文件根= Environment.getExternalStorageDirectory();
        如果(root.canWrite()){
            的System.out.println(可以写。);
            文件def_file =新的文件(根,default.txt);
            FileWriter的FW =新的FileWriter(def_file);
            BufferedWriter将出=新的BufferedWriter(FW);
            字符串defbuf =默认;
            out.write(defbuf);
            了out.flush();
            out.close();
        }
        其他
            的System.out.println(可以不写。);
}赶上(IOException异常E){
        e.printStackTrace();
}
 

root.canWrite()似乎返回false每次。我不运行这个功能的仿真器,我有我的android厄里斯通过USB接口和通过Eclipse运行应用程序,从我的手机插在我的电脑。是否有给予我的应用程序权限的方式,使这不会发生?

此外,该code看来,如果它已经存在,是创建文件 default.txt 但是,将它忽略了创作,只是打开它来写或者我必须赶上像 FileAlreadyExists (如果存在这样的例外),然后只需打开它,并写?

感谢您的帮助球员。

解决方案   

有没有给予我的应用程序的方式   权限,以便这不会发生?

您需要的 WRITE_EXTERNAL_STORAG​​E 许可。

Win10 环境下 SD 卡烧录 U boot 时出现 can not write image

您还需要没有SD卡安装在您的开发机器 - 无论是在同一时间在电脑或手机都可以访问SD卡,但不能同时

Sorry for the ambiguous title but I'm doing the following to write a simple string to a file:

try {
        File root = Environment.getExternalStorageDirectory();
        if (root.canWrite()){
            System.out.println("Can write.");
            File def_file = new File(root, "default.txt");
            FileWriter fw = new FileWriter(def_file);
            BufferedWriter out = new BufferedWriter(fw);
            String defbuf = "default";
            out.write(defbuf);
            out.flush();
            out.close();
        }
        else
            System.out.println("Can't write.");
}catch (IOException e) {
        e.printStackTrace();
}

But root.canWrite() seems to be returning false everytime. I am not running this off of an emulator, I have my android Eris plugged into my computer via USB and running the app off of my phone via Eclipse. Is there a way of giving my app permission so this doesn't happen?

Also, this code seems to be create the file default.txt but what if it already exists, will it ignore the creation and just open it to write or do I have to catch something like FileAlreadyExists(if such an exception exists) which then just opens it and writes?

Thanks for any help guys.

解决方案

Is there a way of giving my app permission so this doesn't happen?

You need the WRITE_EXTERNAL_STORAGE permission.

You also need to not have the SD card mounted on your development machine -- either the computer or the phone can access the SD card, but not both at the same time.