Android:问题创建目录

时间:2015-10-15 13:38:07

标签: java android file sd-card

我正在尝试在gallery文件夹中创建一个目录(仅用于存储视频和照片),我试过这段代码:

 File dir = new File(Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DCIM + "/dirname");
 dir.makedirs() ;

问题是当我使用文件管理器浏览SD卡文件和文件夹时一切正常并且文件确实存在,但是当我打开我的库时,没有名为dirname的目录。有什么问题?

谢谢: - )

2 个答案:

答案 0 :(得分:0)

尝试getAbsolutePath()

String filePathDir = Environment.getExternalStorageDirectory()
            .getAbsolutePath()
            + "/"
            + appNameFolder
            + "/"
            + innerFolder;
File fileDir = new File(filePathDir);
if (!fileDir.exists())
    fileDir.mkdirs();

答案 1 :(得分:0)

这是我的函数,它采用位图并将其保存在目录中......

 public void saveBitmap(Bitmap bitmap) {

    if (createDirIfNotExists("TestApp")) {
        String filePath = Environment.getExternalStorageDirectory()
                + File.separator + "TestApp/TestSC" + date_value + "_" + time_value + ".png";
        File imagePath = new File(filePath);
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(imagePath);
            bitmap.compress(CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
            hideLoadingDialog();
            showAlert(getString(R.string.successfullySavedPic));
        } catch (FileNotFoundException e) {
            hideLoadingDialog();
            showAlert(getString(R.string.problemOccured));
            Log.e("error", e.getMessage(), e);
        } catch (IOException e) {
            hideLoadingDialog();
            showAlert(getString(R.string.problemOccured));
            Log.e("error", e.getMessage(), e);
        }
    } else {
        String filePath = Environment.getExternalStorageDirectory()
                + File.separator + "Pictures/TestSC" + date_value + "_" + time_value + ".png";
        File imagePath = new File(filePath);
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(imagePath);
            bitmap.compress(CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
            hideLoadingDialog();
            showAlert(getString(R.string.successfullySavedPic));
        } catch (FileNotFoundException e) {
            hideLoadingDialog();
            showAlert(getString(R.string.successfullySavedPic));
            Log.e("error", e.getMessage(), e);
        } catch (IOException e) {
            hideLoadingDialog();
            showAlert(getString(R.string.successfullySavedPic));
            Log.e("error", e.getMessage(), e);
        }
    }


}

createDirIfNotExist():

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