Home > Back-end >  How to create folder if not exists inside files of app android
How to create folder if not exists inside files of app android

Time:03-10

I'm going to create a folder where save my files png. The name of folder is based on current day. I've tried to put "day" "/" inside outputstream but not working, it's say illegal separator.

This is my code:

 try {
        Date c = Calendar.getInstance().getTime();
        System.out.println("Current time => "   c);

        SimpleDateFormat df = new SimpleDateFormat("dd_MM_yyyy", Locale.getDefault());
        SimpleDateFormat dforario = new SimpleDateFormat("HH_mm_ss", Locale.getDefault());

        String nomeFile = df.format(c)   "/"   tavolaScelta   "_rotazione_parte_"  i    "_"   dforario.format(c)   ".png";

        FileOutputStream fileOutputStream = openFileOutput(nomeFile, Context.MODE_PRIVATE);
        frameLayoutBitmapped.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
        fileOutputStream.close();

     } catch (Exception e) {
         e.printStackTrace();
     }

The result i expect is:

08_03_2022 (this is a directory for each day) ---> R1_R1_rotazione_parte_1_16_23.png (this is file of image)

Thanks for any help.

CodePudding user response:

String nomeFile = df.format(c) "/" tavolaScelta "rotazione_parte" i "_" dforario.format(c) ".png";

The name of the file should be a name only.

So it cannot contain / characters.

It makes no sense to try to create your own subdirs if you use openFileOutput() as the file will just land in getFilesDir().

If you want to create your own subdirs in getFilesDir() then create them first with mkdirs() and then use new FileOutputStream() to create the file in it.

File dir = new File(getFilesDir(), "myfolder/yetafolder");
if ( ! dir.exists() )
   if ( !dir.mkdirs())
      return;

File file = new File (dir, "myfilename.png");

FileOutputStream fos = new FileOutputStream(file);
  • Related