0

I am trying to copy some Files to SD Card and then delete them . But many times the files are not getting copied and only getting Deleted.

And also many times the FileInputStreamis null where as i am checking if the file which has to be transferred exists or not and also if it is writable or not.

This is the Code i am using to move a file

  public static void move(final File remove,final DocumentFile move_to_folder) {

            final  String mime = MimeTypes.getMimeType(remove);


                    final   DocumentFile move = move_to_folder.createFile(mime, remove.getName());

                    try {
                        inStream = new FileInputStream(remove);
                        outStream =
                                con.getApplicationContext().getContentResolver().openOutputStream(move.getUri());
                        final byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = inStream.read(buffer)) != -1) {
                            outStream.write(buffer, 0, bytesRead);    
                        } 

                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if(inStream!=null)
                            {
                                inStream.close();
                            }                                
                           if(outStream!=null)
                            {
                                outStream.close();                                   
                            }
                              delete(remove);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
    }

I am transferring many files at a time so i am using this code inside an Async Task .

Any help would be really Grateful.

Rahulrr2602
  • 701
  • 1
  • 13
  • 34

1 Answers1

1

If you have an exception, the remove gets deleted without consideration

Consider adding a boolean flag to prevent this

e.g.

before the try block add

boolean canDelete = true;

If you have an exception set

canDelete = false;

and then in the finally check this boolean

if (canDelete) 
   delete(remove);
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64