如何在android中的sdcard中创建文件夹

 孟倩-951127 发布于 2023-02-04 18:57

我想在我的SD卡中创建文件夹,我使用了以下代码:

public class Screen extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.welcome);

        operateOnFirstUsage();
    }

    private void operateOnFirstUsage() {

        String state = Environment.getExternalStorageState();
        Log.d("Media State", state);

        if (Environment.MEDIA_MOUNTED.equals(state)) {
            File appDirectory = new File(
                    Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyApp/");

            Log.d("appDirectroyExist", appDirectory.exists() + "");
            if (!appDirectory.exists()) 
                Log.d("appDir created: ", appDirectory.mkdir() + "");

            File dbDirectory = new File(
                    Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyApp/Database/");

            Log.d("dbDirectroyExist", dbDirectory.exists() + "");
            if (!dbDirectory.exists())
                Log.d("dbDir created: ", dbDirectory.mkdirs() + "");


            File themesDirectory = new File(
                    Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyApp/Themes/");
            Log.d("themesDirectroyExist", themesDirectory.exists() + "");
            if (!themesDirectory.exists()) 
                Log.d("themesDir created: ", themesDirectory.mkdirs() + "");

        }
    }
}

另外,我设置了sdcard写权限:


每次运行LogCat输出时,我都会多次运行应用程序:

01-09 21:38:13.701: D/Media State(15363): mounted
01-09 21:38:13.701: D/appDirectroyExist(15363): false
01-09 21:38:13.701: D/appDir created:(15363): false
01-09 21:38:13.701: D/dbDirectroyExist(15363): false
01-09 21:38:13.701: D/dbDir created:(15363): false
01-09 21:38:13.701: D/themesDirectroyExist(15363): false
01-09 21:38:13.701: D/themesDir created:(15363): false

我读过类似的问题,但没有什么用处.我该怎么做才能让代码运行?我的问题是什么?

1 个回答
  • 编辑

    试试这个:

    File mydir = new File(Environment.getExternalStorageDirectory() + "/mydir/");
    if(!mydir.exists())
        mydir.mkdirs();
    else
        Log.d("error", "dir. already exists");
    

    并重新检查权限

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    2023-02-04 19:00 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有