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

发布于 2024-08-18 21:13:15 字数 289 浏览 2 评论 0原文

我正在尝试将文件保存到以下位置
FileOutputStream fos = new FileOutputStream("/sdcard/Wallpaper/"+fileName); 但我收到异常 java.io.FileNotFoundException
但是,当我将路径设置为 "/sdcard/" 时,它就可以工作了。

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

有人可以建议如何使用代码创建目录和子目录吗?

I'm trying to save my file to the following location
FileOutputStream fos = new FileOutputStream("/sdcard/Wallpaper/"+fileName);
but I'm getting the exception java.io.FileNotFoundException
However, when I put the path as "/sdcard/" it works.

Now I'm assuming that I'm not able to create directory automatically this way.

Can someone suggest how to create a directory and sub-directory using code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

注定孤独终老 2024-08-25 21:13:15

如果您创建一个包含顶级目录的 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);

注意: 使用 Environment.getExternalStorageDirectory() 用于获取“SD 卡”目录,因为如果手机配备 SD 卡以外的其他设备(例如内置闪存、a'la iPhone)。无论哪种方式,您都应该记住,您需要检查以确保它确实存在,因为 SD 卡可能会被移除。

更新:自 API 级别 4 (1.6) 起,您还必须请求权限。像这样的东西(在清单中)应该有效:

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

If you create a File object that wraps the top-level directory you can call it's mkdirs() method to build all the needed directories. Something like:

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

Note: It might be wise to use Environment.getExternalStorageDirectory() for getting the "SD Card" directory as this might change if a phone comes along which has something other than an SD Card (such as built-in flash, a'la the iPhone). Either way you should keep in mind that you need to check to make sure it's actually there as the SD Card may be removed.

UPDATE: Since API Level 4 (1.6) you'll also have to request the permission. Something like this (in the manifest) should work:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
我喜欢麦丽素 2024-08-25 21:13:15

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

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

Had the same problem and just want to add that AndroidManifest.xml also needs this permission:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
溺渁∝ 2024-08-25 21:13:15

这对我有用。

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

Here is what works for me.

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

in your manifest and the code below

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;
}
诗笺 2024-08-25 21:13:15

实际上我使用了 @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");

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

Actually I used part of @fiXedd asnwer and it worked for me:

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

Make sure that you are using mkdirs() not mkdir() to create the complete path

绾颜 2024-08-25 21:13:15

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

您可以在SDK 文档中阅读更多信息。

With API 8 and greater, the location of the SD card has changed. @fiXedd's answer is good, but for safer code, you should use Environment.getExternalStorageState() to check if the media is available. Then you can use getExternalFilesDir() to navigate to the directory you want (assuming you're using API 8 or greater).

You can read more in the SDK documentation.

°如果伤别离去 2024-08-25 21:13:15

确保存在外部存储:
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);
    }

Make sure external storage is present:
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);
    }
放飞的风筝 2024-08-25 21:13:15

不要忘记确保文件/文件夹名称中没有特殊字符。当我使用变量设置文件夹名称时,出现“:”,

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

" * / : <> ? \ |

在这种情况下,您可能会发现此代码很有帮助。

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

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

Don't forget to make sure that you have no special characters in your file/folder names. Happened to me with ":" when I was setting folder names using variable(s)

not allowed characters in file/folder names

" * / : < > ? \ |

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");
        }
    }
月竹挽风 2024-08-25 21:13:15
     //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);
     //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);
对岸观火 2024-08-25 21:13:15

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

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

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();
樱娆 2024-08-25 21:13:15
File sdcard = Environment.getExternalStorageDirectory();
File f=new File(sdcard+"/dor");
f.mkdir();

这将在您的 SD 卡中创建一个名为 dor 的文件夹。
然后获取例如 filename.json 的文件,该文件手动插入到 dor 文件夹中。喜欢:

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

<使用权限 android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

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

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

热血少△年 2024-08-25 21:13:15

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

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

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();
        }
罪#恶を代价 2024-08-25 21:13:15

刚刚完成 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
}

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
}
献世佛 2024-08-25 21:13:15
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);

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

        }
    });`
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文