programing

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

javajsp 2023. 9. 1. 20:36

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

파일을 다음 위치에 저장하려고 합니다.
FileOutputStream fos = new FileOutputStream("/sdcard/Wallpaper/"+fileName);하지만 저는 예외입니다.java.io.FileNotFoundException
하지만, 내가 그 길을 다음과 같이 말할 때."/sdcard/"그건 효과가 있다.

이제 이런 식으로 디렉토리를 자동으로 작성할 수 없다고 가정합니다.

누가 어떻게 만들 것인지 제안해 줄 수 있습니까?directory and sub-directory코드를 사용하시겠습니까?

최상위 디렉터리를 감싸는 File 개체를 생성하면 필요한 모든 디렉터리를 빌드하는 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 a'la)이 포함된 전화기가 제공되는 경우 변경될 수 있습니다.어느 쪽이든 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;
}

사실 저는 @fiXed의 답변의 일부를 사용했고 그것은 저에게 효과가 있었습니다.

  //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()가 아닌 mkdir()를 사용해야 합니다.

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);
    }

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

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

" * / : < > ? \ |

이러한 경우 이 코드가 유용할 수 있습니다.

아래 코드는 모든 ":"를 제거하고 "-"로 대체합니다.

//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");
        }
    }
     //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);

갤럭시S에서 디렉터리를 만들 수는 없었지만 넥서스와 삼성 드로이드에서 성공적으로 디렉터리를 만들 수 있었습니다.제가 수정한 방법은 다음 코드 행을 추가하는 것이었습니다.

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

이렇게 하면 sdcard에 dor라는 이름의 폴더가 생성됩니다.그런 다음 dor 폴더에 수동으로 삽입된 eg-filename.json 파일을 가져옵니다.예:

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

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

매니페스트에 코드를 추가하는 것을 잊지 마세요.

이렇게 하면 제공한 폴더 이름으로 sdcard에 폴더가 만들어집니다.

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

Vijay의 게시물을 작성하는 중...


매니페스트

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;
}

사용.

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

오류를 확인할 수 있습니다.

if(createDirIfNotExists("mydir/")){
     //Directory Created Success
}
else{
    //Error
}
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