development

/ sdcard에 디렉토리 생성 실패

big-blog 2020. 12. 31. 23:19
반응형

/ sdcard에 디렉토리 생성 실패


/sdcard프로그래밍 방식 으로 디렉터리를 만들려고 했지만 작동하지 않습니다. 아래 코드는 항상 출력directory not created.

boolean success = (new File("/sdcard/map")).mkdir(); 
if (!success) {
    Log.i("directory not created", "directory not created");
} else {
    Log.i("directory created", "directory created");
}

여기에서 고려해야 할 세 가지 사항이 있습니다.

  1. sd 카드가에 마운트되어 있다고 가정하지 마십시오 /sdcard(기본 경우에 해당 할 수 있지만 하드 코딩하지 않는 것이 좋습니다). 시스템을 쿼리하여 sdcard의 위치를 ​​가져올 수 있습니다.

    Environment.getExternalStorageDirectory();
    
  2. AndroidManifest.xml 파일 에 사용 권한 항목을 추가하여 애플리케이션이 외부 저장소에 기록해야 함을 Android에 알려야 합니다.

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
  3. 이 디렉토리가 이미 존재하는 경우 mkdir은 false를 반환합니다. 따라서 디렉토리가 있는지 확인한 다음 존재하지 않으면 생성 해보십시오. 구성 요소에서 다음과 같이 사용하십시오.

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

Android 폰을 6.0 (API 레벨 23)으로 업데이트 한 후에도 동일한 문제가 발생했습니다. 다음 솔루션이 저에게 효과적입니다. 바라건대 그것은 당신에게도 도움이되기를 바랍니다.

Android 버전을 확인하세요. 6.0 (API 레벨 23) 이상이면 다음을 포함해야합니다.

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

AndroidManifest.xml에 있지만 mkdir ()을 호출하기 전에 권한요청하십시오 . 코드 스 놉샷.

public static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
public int mkFolder(String folderName){ // make a folder under Environment.DIRECTORY_DCIM
    String state = Environment.getExternalStorageState();
    if (!Environment.MEDIA_MOUNTED.equals(state)){
        Log.d("myAppName", "Error: external storage is unavailable");
        return 0;
    }
    if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        Log.d("myAppName", "Error: external storage is read only.");
        return 0;
    }
    Log.d("myAppName", "External storage is not read only or unavailable");

    if (ContextCompat.checkSelfPermission(this, // request permission when it is not granted. 
            Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        Log.d("myAppName", "permission:WRITE_EXTERNAL_STORAGE: NOT granted!");
        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

            // Show an expanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    }
    File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),folderName);
    int result = 0;
    if (folder.exists()) {
        Log.d("myAppName","folder exist:"+folder.toString());
        result = 2; // folder exist
    }else{
        try {
            if (folder.mkdir()) {
                Log.d("myAppName", "folder created:" + folder.toString());
                result = 1; // folder created
            } else {
                Log.d("myAppName", "creat folder fails:" + folder.toString());
                result = 0; // creat folder fails
            }
        }catch (Exception ecp){
            ecp.printStackTrace();
        }
    }
    return result;
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

자세한 내용은 " 런타임시 권한 요청 "을 참조 하십시오 .


sdcard의 올바른 경로는 다음과 같습니다.

/mnt/sdcard/

그러나 이전에 대답했듯이 하드 코딩해서는 안됩니다. Android 2.1 이상을 사용하는 경우

getExternalFilesDir(String type) 

그렇지 않으면:

Environment.getExternalStorageDirectory()

https://developer.android.com/guide/topics/data/data-storage.html#filesExternal을 주의 깊게 읽으십시오.

또한이 방법 또는 유사한 방법을 사용해야합니다.

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
    // We can read and write the media
    mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    // We can only read the media
    mExternalStorageAvailable = true;
    mExternalStorageWriteable = false;
} else {
    // Something else is wrong. It may be one of many other states, but all we need
    //  to know is we can neither read nor write
    mExternalStorageAvailable = mExternalStorageWriteable = false;
}

then check if you can access the sdcard. As said, read the official documentation.

Another option, maybe you need to use mkdirs instead of mkdir

file.mkdirs()

Creates the directory named by the trailing filename of this file, including the complete directory path required to create this directory.


Restart your Android device. Things started to work for me after I restarted the device.


If this is happening to you with Android 6 and compile target >= 23, don't forget that we are now using runtime permissions. So giving permissions in the manifest is not enough anymore.


use mkdirs() instead of mkdir()..it worked for me :)

File folder = new File(Environment.getExternalStorageDirectory()+"/Saved CGPA");
if(!folder.exists()){
    if(folder.mkdirs())
    Toast.makeText(this, "New Folder Created", Toast.LENGTH_SHORT).show();
}

File sdCardFile = new File(Environment.getExternalStorageDirectory()+"/Saved CGPA/cgpa.html");

in android api >= 23

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

instead of

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

Do you have the right permissions to write to SD card in your manifest ? Look for WRITE_EXTERNAL_STORAGE at http://developer.android.com/reference/android/Manifest.permission.html


Isn't it already created ? Mkdir returns false if the folder already exists too mkdir


There are Many Things You Need to worry about 1.If you are using Android Bellow Marshmallow then you have to set permesions in Manifest File. 2. If you are using later Version of Android means from Marshmallow to Oreo now Either you have to go to the App Info and Set there manually App permission for Storage. if you want to Set it at Run Time you can do that by below code

public  boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
    if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
            == PackageManager.PERMISSION_GRANTED) {
        Log.v(TAG,"Permission is granted");
        return true;
    } else {

        Log.v(TAG,"Permission is revoked");
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        return false;
    }
}
else { //permission is automatically granted on sdk<23 upon installation
    Log.v(TAG,"Permission is granted");
    return true;
}

}


File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
        + "/FoderName");
if (!f.exists()) {
    f.mkdirs();
}

I made the mistake of including both:

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

and:

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

in the above order. So when I took out the second permission, (READ), the problem went away.

ReferenceURL : https://stackoverflow.com/questions/3853472/creating-a-directory-in-sdcard-fails

반응형