android - 在外部 SD 卡中创建文件

标签 android file storage android-sdcard sd-card

我是 Android 开发新手。 我想在我的外部 SD 卡中创建一个文件。我搜索了很多并尝试了不同的代码。但它是在设备存储中创建的,或者根本不创建。 我得到了我的 SD 卡路径,它位于/mnt/extSdCard 中。 我什至尝试了几个代码,但没有一个不起作用。 此代码找到了我的 SD 卡位置:

 public static String getExternalSdCardPath() {
    String path = null;

    File sdCardFile = null;
    List<String> sdCardPossiblePath = Arrays.asList("external_sd", "ext_sd", "external", "extSdCard");

    for (String sdPath : sdCardPossiblePath) {
        File file = new File("/mnt/", sdPath);

        if (file.isDirectory() && file.canWrite()) {
            path = file.getAbsolutePath();
            Log.i("LOG", "path is: " + path);

            String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
            File testWritable = new File(path, "test_" + timeStamp);
            if (testWritable.mkdirs()) {
                testWritable.delete();
            } else {
                path = null;
            }
        }
    }

    if (path != null) {
        sdCardFile = new File(path);
    } else {
        sdCardFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
    }
    return sdCardFile.getAbsolutePath();
}

路径是我的位置。

最佳答案

以下是如何使用代码设置 SD 卡路径(如果您没有 SD 卡,Android 将仅将数据存储在内部存储中) 首先在启动Activity时声明这个变量

public static String THE_PATH;

然后在同一个Activity中的onCreate Bundle中调用这个方法onAvail()

    // Is External Storage Available if so use it and desi the path for DBHelper
public void onAvail() {

    String state = Environment.getExternalStorageState();

    if (state.equals(Environment.MEDIA_MOUNTED) && 

(!state.equals(Environment.MEDIA_MOUNTED_READ_ONLY))) {

        File removable = ContextCompat.getExternalFilesDirs(this, null)[1];
        THE_PATH = String.valueOf(removable);
        //System.out.println("EXTERNAL PATH ====> " + THE_PATH);
        THE_PATH = THE_PATH + "/Documents/";
        //System.out.println("new path ====> "+THE_PATH);
    }
}

我希望你有一个 DBHelper 类,这是该类中发生的事情

import static <app name here>.MainActivity.THE_PATH;

 // Variable str is set in MainActivity as Public static
// to be accessible in the DBHelper Class 

//从 MainAvtivity 调用

公共(public)类 DBHelper 扩展 SQLiteOpenHelper {

public static final String DB_NAME = THE_PATH +"PassWord";

关于android - 在外部 SD 卡中创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45533601/

相关文章:

mongodb - 调整 PVC 大小的问题 : Only dynamically provisioned pvc can be resized and the storageclass that provisions the pvc must support resize

c - 我 free() 一个指向结构的指针,但它的属性仍然存在。这怎么可能?

android - 无法从 NumberPicker 中选择数字

android - appWidget 仅在 Lollipop 设备的启动器小部件列表中不显示

c - 从函数返回 FILE 指针并在 main 上处理它

java 文件重命名()

Silverlight 将 byte[] 转换为图像的字符串

Android转场动画线性交叉淡入淡出效果

android - React Native assembleRelease无法使用axios获取数据

linux - 如何在 Rust 中获取打开的 std::fs::File 的文件名?