skip to Main Content

Here is My Code the way I’m creating my folder in app Specific directory.

  private File createDirectory(String dirName) {
    File file = new File(getApplicationContext().getExternalFilesDir(dirName) + "/" + dirName);
    if (!file.exists()) {
        file.mkdir();
    }
    return file;
}

3

Answers


  1. your method returns File, which is a directory. now you have to create new image file object

    File dir = createDirectory("imagesDirectory");
    File file = new File(dir.getAbsolutePath(), "imageName.jpg");
    FileOutputStream outStream = new FileOutputStream(file);
    

    now you have to compress your Bitmap as JPG (as name set above) and feed this stream

    Bitmap pictureBitmap = ...; // your image
    pictureBitmap.compress(Bitmap.CompressFormat.JPEG, 90, outStream); 
    

    and don’t foregt to close stream

    outStream.flush();
    outStream.close();
    

    if you want lossless format you can use PNG (Bitmap.CompressFormat.PNG), don’t forget to name your file extension accordingly

    Login or Signup to reply.
  2. you can only write in your app-specific files

    File dir_ = new File(context.getFilesDir(), "YOUR_DIR");
    dir_.mkdirs();
    
    Login or Signup to reply.
  3. you can use the function "getExternalFilesDir" and you change the value between in parenthesis. Here I put "Environment.DIRECTORY8DCIM" but there are others (you can check in the android developer web site).

    I show you an exemple:

    private fun getOutputMediaFile(): File? {
    
    
            val mediaStorageDir = getExternalFilesDir(Environment.DIRECTORY_DCIM).let {
                    File(it, "[name_folder]").apply { mkdirs() } }
    
            Log.v(TAG, "storage: $mediaStorageDir") ///storage/emulated/0/Android/data/[name_of_your_program]/files/DCIM/[name_folder]
    
            if (!mediaStorageDir?.exists()!!){
                if (!mediaStorageDir.mkdirs()) {
                    Log.v(TAG, "Failed to create directory")
                    return null
                }
            }
    }
    

    Hope that work for you 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search