Today we are going to take a look at how to programmatically “copy” or “move” a file from one directory to another on Android. In case you want to be clarified about the difference, copying a file means the file will be seen on another directory (target location) without deleting the original file from the source location. Moving a file means the file will be seen in another directory and the original file will be deleted from its former location.
Here are some situations where I found these functionalities helpful:
- Copying a file to another directory is useful when you have to save a file’s version or state in specific time.
- Moving a file to another directory can be an advantage when you want to remove a file from a main folder of your application and make it an archive.
Before running this code, you have to:
- Place an example text file named “sample.txt” (with any text inside) in your SD card root.
- Create a directory called “MyNewFolder” in your SD card root directory also.
Our MainActivity.java
package com.example.copyfilefromdirectorytoanother; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.app.Activity; public class MainActivity extends Activity { private static final String TAG = "MainActivity.java"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // your sd card String sdCard = Environment.getExternalStorageDirectory().toString(); // the file to be moved or copied File sourceLocation = new File (sdCard + "/sample.txt"); // make sure your target location folder exists! File targetLocation = new File (sdCard + "/MyNewFolder/sample.txt"); // just to take note of the location sources Log.v(TAG, "sourceLocation: " + sourceLocation); Log.v(TAG, "targetLocation: " + targetLocation); try { // 1 = move the file, 2 = copy the file int actionChoice = 2; // moving the file to another directory if(actionChoice==1){ if(sourceLocation.renameTo(targetLocation)){ Log.v(TAG, "Move file successful."); }else{ Log.v(TAG, "Move file failed."); } } // we will copy the file else{ // make sure the target file exists if(sourceLocation.exists()){ InputStream in = new FileInputStream(sourceLocation); OutputStream out = new FileOutputStream(targetLocation); // Copy the bits from instream to outstream byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); Log.v(TAG, "Copy file successful."); }else{ Log.v(TAG, "Copy file failed. Source file missing."); } } } catch (NullPointerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
Logcat ouput when we move a file looks like this:
Logcat output when copying a file failed:
Thanks for reading this Copy or Move File From One Directory to Another on Android!
13 responses to “Copy or Move File From One Directory to Another on Android”
Is renameTo() the best method? I found someone use the java.nio.file class, but it cannot be imported in Android.
Hey @WffgerYu:disqus , renameTo() method is what works for me, would you link us to that class, we might find another way to spin it around! :)
http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#copy(java.nio.file.Path,%20java.nio.file.Path,%20java.nio.file.CopyOption…)
Thanks for sharing @WffgerYu:disqus , we’ll look into it!
what happens if we already have a file in the target location with the same name, it will prompt us to overwrite it, or our app will crash?…
also, how to proceed to copy from internal storage (/data/data/com.example/shared_prefs/test.txt) to sdcard (/downloads/test.txt) and viceversa from sdcard to internal storage.
I want to import/export my favorites but i’m very beginner and a help would be appreciated.Thanks in advance.
Hello @ciupercomania:disqus , I believe it will overwrite it. The best way to know is to do some testing. Copy from storage and vice versa can be done, you just have to specify the correct source and target locations.
Thank you so much, it was a great help. BTW can you also tell me how can I change the extension of the file while writing it to the target location?
You’re welcome @abhishekmandloi:disqus! Glad to help you! About your question, you can try changing the “.txt” in the string to your extension of choice.
Okay will try it, thanks :)
You’re welcome @abhishekmandloi:disqus!
hi mike would u pls help me in cart shop function espicially in adding and updating quantity..i would be very greatful if u did..just give me the source code for adding and updating quantity thats all what i want bro bcoz i hv presentation tmmorow morning..thx
Hello @disqus_oySNFLELX3:disqus, unfortunately, our android shopping cart source code is not yet available, but we’re working on it.
Hi Mike. I copied an image “a.png” in my sdCard folder. I used the code you mentioned. However it is not doing anything. I checked the manifest and added write permission as well. Could you suggest me something?