简体   繁体   English

如何在Android应用程序中以编程方式格式化SD卡?

[英]How can I format SD card in android application programmatically?

How can i format the SD card inside the mobile by implementing the code for "formatting SD card" in an application? 如何通过在应用程序中实现“格式化SD卡”的代码来格式化手机内部的SD卡? im currently using this code, but i cant get it to work. 我目前正在使用此代码,但我无法使其正常工作。

    public void wipingSdcard(View view) {
        File deleteMatchingFile = new File(Environment
                .getExternalStorageDirectory().toString());
        try {
            File[] filenames = deleteMatchingFile.listFiles();
            if (filenames != null && filenames.length > 0) {
                for (File tempFile : filenames) {
                    if (tempFile.isDirectory()) {
                        wipeDirectory(tempFile.toString());
                        tempFile.delete();
                    } else {
                        tempFile.delete();
                    }
                }
            } else {
                deleteMatchingFile.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void wipeDirectory(String name) {
        File directoryFile = new File(name);
        File[] filenames = directoryFile.listFiles();
        if (filenames != null && filenames.length > 0) {
            for (File tempFile : filenames) {
                if (tempFile.isDirectory()) {
                    wipeDirectory(tempFile.toString());
                    tempFile.delete();
                } else {
                    tempFile.delete();
                }
            }
        }
    }

And i am also using android:onClick="wipingSdcard" in my xml.code for the "format sd card" button. 而且我还在xml.code中使用android:onClick =“ wipingSdcard”作为“格式化SD卡”按钮。

What am i doing wrong? 我究竟做错了什么?

Actually, you cannot format an SD Card by deleting all of its files and folders. 实际上,您无法通过删除SD卡的所有文件和文件夹来对其进行格式化。 Imagine that SD Card is unformatted, you can't just delete the files inside it, because the operating system doesn't know what filesystem it uses. 想象一下SD卡是未格式化的,您不能只删除其中的文件,因为操作系统不知道它使用的文件系统。

也包括这些权限。

MOUNT_FORMAT_FILESYSTEMS

MOUNT_UNMOUNT_FILESYSTEMS

Does wipeDirectory(tempFile.toString()); 是否擦拭目录(tempFile.toString()); give the right parameter? 给正确的参数?

I mean, is tempFile.toString() the same as tempFile.getPath().toString() ? 我的意思是,tempFile.toString()与tempFile.getPath()。toString()一样吗? It could be this. 可能就是这个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM