如何在SD卡上自动创建目录

Ksh*_*wal 185 android android-file

我正在尝试将我的文件保存到以下位置,
FileOutputStream fos = new FileOutputStream("/sdcard/Wallpaper/"+fileName); 但是我得到了异常java.io.FileNotFoundException
但是,当我把路径保存"/sdcard/"起来的时候.

现在我假设我无法以这种方式自动创建目录.

有人可以建议如何创建directory and sub-directory使用代码吗?

Jer*_*gan 443

如果您创建一个包装顶级目录的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);
Run Code Online (Sandbox Code Playgroud)

注意:使用Environment.getExternalStorageDirectory()来获取"SD卡"目录可能是明智之举,因为如果手机出现了除SD卡以外的其他东西(例如内置闪存,则可能会更改)苹果手机).无论哪种方式,您都应该记住,您需要检查以确保它实际存在,因为可能会移除SD卡.

更新:自API级别4(1.6)起,您还必须请求许可.这样的事情(在清单中)应该有效:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Run Code Online (Sandbox Code Playgroud)

  • 不适用于KitKat,外部物理SD卡. (4认同)
  • 没问题.乐于帮助. (2认同)
  • 别忘了添加到AndroidManifest.xml的权利写http://stackoverflow.com/a/4435708/579646 (2认同)

Dan*_*iel 57

有同样的问题,只想添加AndroidManifest.xml也需要此权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Run Code Online (Sandbox Code Playgroud)


Vij*_*A B 39

这对我有用.

 uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" 
Run Code Online (Sandbox Code Playgroud)

在你的清单和下面的代码中

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;
}
Run Code Online (Sandbox Code Playgroud)


Amt*_*t87 24

实际上我使用@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");
Run Code Online (Sandbox Code Playgroud)

确保使用mkdirs()而不是mkdir()来创建完整路径


Nic*_*uiz 12

使用API​​ 8及更高版本,SD卡的位置已更改.@ fiXedd的答案很好,但是为了更安全的代码,你应该Environment.getExternalStorageState()用来检查媒体是否可用.然后,您可以使用getExternalFilesDir()导航到所需的目录(假设您使用的是API 8或更高版本).

您可以在SDK文档中阅读更多内容.


Par*_*hta 8

确保存在外部存储: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);
    }
Run Code Online (Sandbox Code Playgroud)


Pra*_*een 6

不要忘记确保文件/文件夹名称中没有特殊字符.当我使用变量设置文件夹名称时,用":"发生在我身上

不允许文件/文件夹名称中的字符

"*/:<>?\ |

你可能会发现这个代码在这种情况下很有帮助.

下面的代码删除所有":"并用" - "替换它们

//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");
        }
    }
Run Code Online (Sandbox Code Playgroud)


小智 6

     //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);
Run Code Online (Sandbox Code Playgroud)


小智 6

我遇到了同样的问题.Android中有两种类型的权限:

  • 危险(访问联系人,写入外部存储...)
  • 正常 (Android会自动批准普通权限,而Android用户需要批准危险权限.)

以下是在Android 6.0中获取危险权限的策略

  • 检查您是否已获得许可
  • 如果您的应用已获得许可,请继续正常运行.
  • 如果您的应用尚未获得许可,请要求用户批准
  • 听取用户的批准 onRequestPermissionsResult

这是我的情况:我需要写入外部存储.

首先,我检查一下我是否有权限:

...
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);
}
Run Code Online (Sandbox Code Playgroud)

然后检查用户的批准:

@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();
            }
        }
    }    
}
Run Code Online (Sandbox Code Playgroud)


Gar*_*ava 5

我遇到了同样的问题,无法在Galaxy S上创建目录,但能够在Nexus和Samsung Droid上成功创建目录.我如何修复它是通过添加以下代码行:

File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+getPackageName()+"/");
dir.mkdirs();
Run Code Online (Sandbox Code Playgroud)


jay*_*ngh 5

File sdcard = Environment.getExternalStorageDirectory();
File f=new File(sdcard+"/dor");
f.mkdir();
Run Code Online (Sandbox Code Playgroud)

这将在你的SD卡中创建一个名为dor的文件夹.然后获取eg- filename.json的文件,手动插入dor文件夹.喜欢:

 File file1 = new File(sdcard,"/dor/fitness.json");
 .......
 .....
Run Code Online (Sandbox Code Playgroud)

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

并且不要忘记在清单中添加代码


Shw*_*han 5

这将使用您提供的文件夹名称在 SD 卡中创建文件夹。

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