在安卓中创建文件夹

2022-08-31 21:08:31
 import java.io.File;  
    File folder = new File(Environment.getExternalStorageDirectory() + "/TollCulator");
    boolean success = true;
    if (!folder.exists()) {
        //Toast.makeText(MainActivity.this, "Directory Does Not Exist, Create It", Toast.LENGTH_SHORT).show();
        success = folder.mkdir();
    }
    if (success) {
        //Toast.makeText(MainActivity.this, "Directory Created", Toast.LENGTH_SHORT).show();
    } else {
        //Toast.makeText(MainActivity.this, "Failed - Error", Toast.LENGTH_SHORT).show();
    }

如果SD卡不存在,则上述内容应在我的SD卡中创建一个文件夹,如果存在,则不执行任何操作。尽管 Toast 基于条件工作,但当它不存在时,它不会创建目录。任何想法如何解决它?

我的样子是这样的:Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test.testing"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <uses-sdk
        android:minSdkVersion="6"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.test.testing.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

更新:我更新了清单并更新了代码,但它仍然没有在我的SD卡中创建文件夹。请记住,我正在使用Eclipse并将应用程序直接运行到我的手机(GNex VZW)而不是使用AVD。


答案 1

在 中添加此权限,Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

File folder = new File(Environment.getExternalStorageDirectory() + 
                             File.separator + "TollCulator");
boolean success = true;
if (!folder.exists()) {
    success = folder.mkdirs();
}
if (success) {
    // Do something on success
} else {
    // Do something else on failure 
}

当您运行应用程序时,请去DDMS->文件资源管理器->mnt文件夹->sdcard文件夹>环礁创建文件夹


答案 2

如果您尝试在SD卡的根目录上创建多个文件夹,例如。Environment.getExternalStorageDirectory() + "/Example/Ex App/"

然后代替你会使用folder.mkdir()folder.mkdirs()

我过去犯过这个错误,我花了很长时间才弄清楚。