IT

SD 카드에 자동으로 디렉토리를 만드는 방법

lottoking 2020. 5. 16. 10:37
반응형

SD 카드에 자동으로 디렉토리를 만드는 방법


파일을 다음 위치에 저장하려고하는데
FileOutputStream fos = new FileOutputStream("/sdcard/Wallpaper/"+fileName);예외가 발생합니다. java.io.FileNotFoundException
그러나 경로를 "/sdcard/"작동 시킬 때 예외가 발생 합니다.

이제는이 방법으로 디렉토리를 자동으로 만들 수 없다고 가정합니다.

누군가가 directory and sub-directory사용 코드 를 만드는 방법을 제안 할 수 있습니까 ?


당신이 작성하는 경우 파일의 최상위 디렉토리를 래핑 개체를 당신은 그것의 호출 할 수 있습니다 () mkdirs를 모든 필요한 디렉토리를 구축하는 방법. 다음과 같은 것 :

// create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(wallpaperDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);

참고 : "SD 카드"디렉토리를 가져 오기 위해 Environment.getExternalStorageDirectory () 를 사용하는 것이 현명 할 수 있습니다. 전화기가 SD 카드 이외의 다른 장치 (예 : 내장 플래시, iPhone). 어느 쪽이든 SD 카드를 제거 할 수 있으므로 실제로 있는지 확인해야합니다.

업데이트 : API 레벨 4 (1.6)부터 권한을 요청해야합니다. 매니페스트에서 이와 같은 것이 작동해야합니다.

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

같은 문제가 있었고 AndroidManifest.xml 에도이 권한이 필요하다는 것을 추가하고 싶습니다.

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

여기 나를 위해 일하는 것이 있습니다.

 uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" 

매니페스트와 아래 코드에서

public static boolean createDirIfNotExists(String path) {
    boolean ret = true;

    File file = new File(Environment.getExternalStorageDirectory(), path);
    if (!file.exists()) {
        if (!file.mkdirs()) {
            Log.e("TravellerLog :: ", "Problem creating Image folder");
            ret = false;
        }
    }
    return ret;
}

실제로 나는 @fiXedd asnwer의 일부를 사용했고 그것은 나를 위해 일했다 :

  //Create Folder
  File folder = new File(Environment.getExternalStorageDirectory().toString()+"/Aqeel/Images");
  folder.mkdirs();

  //Save the path as a string value
  String extStorageDirectory = folder.toString();

  //Create New file and name it Image2.PNG
  File file = new File(extStorageDirectory, "Image2.PNG");

전체 경로를 작성하기 위해 mkdir ()이 아닌 mkdirs ()를 사용하고 있는지 확인하십시오.


API 8 이상에서는 SD 카드의 위치가 변경되었습니다. @fiXedd의 답변은 좋지만 더 안전한 코드를 위해서는 Environment.getExternalStorageState()미디어가 사용 가능한지 확인 해야 합니다. 그런 다음 getExternalFilesDir()API 8 이상을 사용한다고 가정하면 원하는 디렉토리로 이동할 수 있습니다 .

SDK 설명서 에서 자세한 내용을 읽을 수 있습니다 .


외부 저장소가 있는지 확인하십시오 : http://developer.android.com/guide/topics/data/data-storage.html#filesExternal

private boolean isExternalStoragePresent() {

        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;
        }
        if (!((mExternalStorageAvailable) && (mExternalStorageWriteable))) {
            Toast.makeText(context, "SD card not present", Toast.LENGTH_LONG)
                    .show();

        }
        return (mExternalStorageAvailable) && (mExternalStorageWriteable);
    }

파일 / 폴더 이름에 특수 문자가 없는지 확인하십시오. 변수를 사용하여 폴더 이름을 설정할 때 ":"로 나에게 일어났습니다.

파일 / 폴더 이름에 허용되지 않는 문자

"* / : <>? \ |

U may find this code helpful in such a case.

The below code removes all ":" and replaces them with "-"

//actualFileName = "qwerty:asdfg:zxcvb" say...

    String[] tempFileNames;
    String tempFileName ="";
    String delimiter = ":";
    tempFileNames = actualFileName.split(delimiter);
    tempFileName = tempFileNames[0];
    for (int j = 1; j < tempFileNames.length; j++){
        tempFileName = tempFileName+" - "+tempFileNames[j];
    }
    File file = new File(Environment.getExternalStorageDirectory(), "/MyApp/"+ tempFileName+ "/");
    if (!file.exists()) {
        if (!file.mkdirs()) {
        Log.e("TravellerLog :: ", "Problem creating Image folder");
        }
    }

I faced the same problem. There are two types of permissions in Android:

  • Dangerous (access to contacts, write to external storage...)
  • Normal (Normal permissions are automatically approved by Android while dangerous permissions need to be approved by Android users.)

Here is the strategy to get dangerous permissions in Android 6.0

  • Check if you have the permission granted
  • If your app is already granted the permission, go ahead and perform normally.
  • If your app doesn't have the permission yet, ask for user to approve
  • Listen to user approval in onRequestPermissionsResult

Here is my case: I need to write to external storage.

First, I check if I have the permission:

...
private static final int REQUEST_WRITE_STORAGE = 112;
...
boolean hasPermission = (ContextCompat.checkSelfPermission(activity,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermission) {
    ActivityCompat.requestPermissions(parentActivity,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                REQUEST_WRITE_STORAGE);
}

Then check the user's approval:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode)
    {
        case REQUEST_WRITE_STORAGE: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                //reload my activity with permission granted or use the features what required the permission
            } else
            {
                Toast.makeText(parentActivity, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
            }
        }
    }    
}

I was facing the same problem, unable to create directory on Galaxy S but was able to create it successfully on Nexus and Samsung Droid. How I fixed it was by adding following line of code:

File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+getPackageName()+"/");
dir.mkdirs();

File sdcard = Environment.getExternalStorageDirectory();
File f=new File(sdcard+"/dor");
f.mkdir();

this will create a folder named dor in your sdcard. then to fetch file for eg- filename.json which is manually inserted in dor folder. Like:

 File file1 = new File(sdcard,"/dor/fitness.json");
 .......
 .....

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

and don't forget to add code in manifest


     //Create File object for Parent Directory
File wallpaperDir = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() +File.separator + "wallpaper");
if (!wallpaperDir.exists()) {
wallpaperDir.mkdir();
}


File out = new File(wallpaperDir, wallpaperfile);
FileOutputStream outputStream = new FileOutputStream(out);

Just completing the Vijay's post...


Manifest

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"

Function

public static boolean createDirIfNotExists(String path) {
    boolean ret = true;

    File file = new File(Environment.getExternalStorageDirectory(), path);
    if (!file.exists()) {
        if (!file.mkdirs()) {
            Log.e("TravellerLog :: ", "Problem creating Image folder");
            ret = false;
        }
    }
    return ret;
}

Usage

createDirIfNotExists("mydir/"); //Create a directory sdcard/mydir
createDirIfNotExists("mydir/myfile") //Create a directory and a file in sdcard/mydir/myfile.txt

You could check for errors

if(createDirIfNotExists("mydir/")){
     //Directory Created Success
}
else{
    //Error
}

This will make folder in sdcard with Folder name you provide.

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Folder name");
        if (!file.exists()) {
            file.mkdirs();
        }

You can use /sdcard/ instead of Environment.getExternalStorageDirectory()

private static String DB_PATH = "/sdcard/Android/data/com.myawesomeapp.app/";

File dbdir = new File(DB_PATH);
dbdir.mkdirs();

ivmage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent i = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(i, RESULT_LOAD_IMAGE_ADD);

        }
    });`

참고URL : https://stackoverflow.com/questions/2130932/how-to-create-directory-automatically-on-sd-card

반응형