Search code examples
javaandroidcopydelete-filestorage-access-framework

File deleted without getting copied


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.


Solution

  • 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);