Prevent saving video file twice in internal storage in android

how to prevent saving the same file selected in galary twice in the internal storage in android. I tried using the code below, it copies the same video many times to a folder in the internal storage.

if (resultCode == RESULT_OK) { Uri uri = data.getData(); new SaveVideoInFolder().execute(uri); try { InputStream is = getContentResolver().openInputStream(uri); File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES); File app_directory = new File(storage, "video_choosing"); if (!app_directory.exists()) app_directory.mkdirs(); String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date()); String filename = String.format("VID_%s.mp4", timestamp); file = new File(app_directory, filename); Toast.makeText(MainActivity.this,file.toString(),Toast.LENGTH_SHORT).show(); OutputStream output = new FileOutputStream(file); byte[] buffer = new byte[4096]; int read; while ((read = is.read(buffer)) != -1) output.write(buffer, 0, read); output.flush(); output.close(); } catch (FileNotFoundException e) { Log.e("TAG", "File Not Found", e); } catch (IOException e) { Log.e("TAG", "IOException", e); } } 
+5
source share
2 answers
 File file = new File(app_directory, filename); if(file.exists()){ ... } else { ... } 
0
source

// Create a storage directory if it does not exist

if (!file.exists()) { if (!file.mkdirs()) { /* Log.e(IMAGE_DIRECTORY_NAME, "Oops! Failed create " + IMAGE_DIRECTORY_NAME + " directory");*/ return null; }

only you will be convinced that your file exists bt if condition and make the directory if it is not.

0
source

All Articles