get Image Filename in yyyyMMdd_HHmmss format - Android android.graphics

Android examples for android.graphics:Image Load Save

Description

get Image Filename in yyyyMMdd_HHmmss format

Demo Code

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class Main{

    public static File getImageFilename(Context context, boolean isPublic)
            throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.US).format(new Date());
        String imageFileName = "IMG_" + timeStamp + ".jpg";

        File storageDir = null;//from  www .jav a  2 s . co  m
        if (isPublic) {
            storageDir = new File(
                    Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                    "Camera");
        } else {
            storageDir = new File(context.getExternalFilesDir(null),
                    "images");
        }

        if (!storageDir.exists()) {
            boolean makeDir = storageDir.mkdirs();
            if (!makeDir) {
                throw new IOException(
                        "Unable to create parent dirs for image file.");
            } else {
                Log.d("","Created parent dir structure for file.");
            }
        }
        File image = new File(storageDir, imageFileName);

        if (image.createNewFile()) {
            Log.d("","Created new image file : "
                    + image.getAbsolutePath());
        } else {
            Log.d("","New file not created; already exists?");
        }

        return image;
    }

}

Related Tutorials