How to move/rename file from internal app storage to external storage on Android?

后端 未结 8 1192
闹比i
闹比i 2020-11-29 02:21

I am downloading files from the internet and saving the streaming data to a temp file in my app\'s internal storage given by getFilesDir().

Once the download is comp

8条回答
  •  伪装坚强ぢ
    2020-11-29 02:46

    Did some trivial modifications to @barmaley's code

    public boolean copyFile(File src, File dst) {
        boolean returnValue = true;
    
       FileChannel inChannel = null, outChannel = null;
    
        try {
    
            inChannel = new FileInputStream(src).getChannel();
            outChannel = new FileOutputStream(dst).getChannel();
    
       } catch (FileNotFoundException fnfe) {
    
            Log.d(logtag, "inChannel/outChannel FileNotFoundException");
            fnfe.printStackTrace();
            return false;
       }
    
       try {
           inChannel.transferTo(0, inChannel.size(), outChannel);
    
       } catch (IllegalArgumentException iae) {
    
             Log.d(logtag, "TransferTo IllegalArgumentException");
             iae.printStackTrace();
             returnValue = false;
    
       } catch (NonReadableChannelException nrce) {
    
             Log.d(logtag, "TransferTo NonReadableChannelException");
             nrce.printStackTrace();
             returnValue = false;
    
       } catch (NonWritableChannelException nwce) {
    
            Log.d(logtag, "TransferTo NonWritableChannelException");
            nwce.printStackTrace();
            returnValue = false;
    
       } catch (ClosedByInterruptException cie) {
    
            Log.d(logtag, "TransferTo ClosedByInterruptException");
            cie.printStackTrace();
            returnValue = false;
    
       } catch (AsynchronousCloseException ace) {
    
            Log.d(logtag, "TransferTo AsynchronousCloseException");
            ace.printStackTrace();
            returnValue = false;
    
       } catch (ClosedChannelException cce) {
    
            Log.d(logtag, "TransferTo ClosedChannelException");
            cce.printStackTrace(); 
            returnValue = false;
    
        } catch (IOException ioe) {
    
            Log.d(logtag, "TransferTo IOException");
            ioe.printStackTrace();
            returnValue = false;
    
    
        } finally {
    
             if (inChannel != null)
    
                try {
    
                   inChannel.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
    
            if (outChannel != null)
                try {
                    outChannel.close();
               } catch (IOException e) {
                    e.printStackTrace();
               }
    
            }
    
           return returnValue;
        }
    

提交回复
热议问题