android - 如何在android DCIM中创建一个新文件夹

标签 android

我实际上能够拍摄照片并将其保存在 android 外部存储 DCIM 文件夹中。

我的问题是我无法在其中创建新文件夹,所以 DCIM/MyPic.jpg 变成了 DCIM/MyFolder/MyPic.jpg

这是我的源代码:

File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "address");

if (!f.exists()) {
    f.mkdir();
}

File file = new File(Environment.getExternalStorageDirectory()
     + File.separator
     + "DCIM"
     + File.separator
     + "address"
     + File.separator
     , "IMG_001.jpg");

请注意,我在 list 中正确请求了 WRITE_EXTERNAL_STORAGE 权限。

捕捉照片的 Intent 部分很好,因为我可以将它直接保存到 DCIM。

我没有收到任何错误消息,但什么也没发生...没有创建“地址”文件夹:(

谢谢你的帮助:D

最佳答案

如评论中所述,我尝试了您的代码,它对我有用。

MainActivity.java

public class MainActivity extends Activity {

    private final static String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "address");

        if (!f.exists()) {
            Log.d(TAG, "Folder doesn't exist, creating it...");
            boolean rv = f.mkdir();
            Log.d(TAG, "Folder creation " + ( rv ? "success" : "failed"));
        } else {
            Log.d(TAG, "Folder already exists.");
        }
    }
}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tristan.testcreatedirectory">

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

</application>

在启动应用程序之前,我必须手动启用权限,因为我使用的是 Android 6。

** 首次启动应用程序时的日志 **

D/MainActivity: Folder doesn't exist, creating it...
D/MainActivity: Folder creation success

** 第二次启动应用时的日志 **

D/MainActivity: Folder already exists.

关于android - 如何在android DCIM中创建一个新文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37557709/

相关文章:

android - NestedScrollView 内的 fragment (Viewpager)未加载

android - android NDK 中的标准 C 字符串

android - 应用程序为什么或何时需要服务器?

android - FFMpeg 估计执行时间

java - JS注入(inject)后Android Webview在进度90%时停止加载

android 将位图转换为缓冲输入流

java - 从 Android 中的可检查 ListView 中删除所有选定的项目

java - 从 HashMap 中排除索引

Android 广播接收器不接收传入的短信

android - 无法在android studio 0.2.3中创建新项目