'How to handle java.io.FileNotFoundException: in FileOutputStream?

I'm using Httpurlconnection and Fileoutstream to write/download file from Internet on android 12.

File file = new File(Environment.getExternalStorageDirectory().getPath() + "/Download" + "/Customfolder");
if (!file.exists()) {
  boolean f = file.mkdir();
            }
File file1 = new File(file, "xyz.apk");
try {
      FileOutputStream fileOutputStream = new FileOutputStream(file1); //got below error from this line
    }catch (Exception e){
      Log.d("LOG",e+"");
                        }

Let's Say I download xyz.apk from abc.com site. When I download for it first time ,there is no error but after deleting xyz.apk from the custom folder and try to download it again, it show me error.

I even tried uninstalling and installing the app again but still gave error when I try to download xyz.apk

 java.io.FileNotFoundException: /storage/emulated/0/Download/Customfolder/xyz.apk: open failed: EEXIST (File exists)

One thing I observed, let say I changed xyz.apk to xxyz.apk before download start than for the first time it will download file but if I again delete it from the custom folder and try to download again with renamed name xxyz.apk , it will throw same error as above.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source