How to copy a file to another saved in SDCARD in Android?

By | December 30, 2012

Hello all…

This tutorial explains how to copy a file contents to another in Android. The file to copy is saved in SDCARD, however you can change the path to save it in your application sandbox.
if you want to save it in your sandbox, change the path to

/data/data/your_packagename/your_file.extension

Now we will see the layout for the program.


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".CopyFileActivity" >

    <TextView
        android:id="@+id/tv1"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <TextView
        android:id="@+id/tv2"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Copy First file to second" />
    
      <TextView
        android:id="@+id/tv3"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

</LinearLayout>

Now this is the java program that does the copying.

package com.coderzheaven.copyfiletoanother;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class CopyFileActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_copy_file);

		Button btn = (Button) findViewById(R.id.btn1);
		TextView tv1 = (TextView) findViewById(R.id.tv1);
		final TextView tv2 = (TextView) findViewById(R.id.tv2);
		final TextView tv3 = (TextView) findViewById(R.id.tv3);

		final String path1 = Environment.getExternalStorageDirectory()
				+ "/first_file.txt";
		final String path2 = Environment.getExternalStorageDirectory()
				+ "/second_file.txt";

		File file1 = new File(path1);
		tv1.setText("First File  : " + file1.getPath() + "(" + file1.length()
				+ " Bytes)\nFirst file contents : \n" + readFromSD(path1));

		File file2 = new File(path2);
		tv2.setText("Second File  : " + file2.getPath() + "(" + file2.length()
				+ " Bytes)");

		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (copyFile(path1, path2))
					Toast.makeText(getApplicationContext(), "File Copied.",
							Toast.LENGTH_LONG).show();
				else
					Toast.makeText(getApplicationContext(), "File Not Copied.",
							Toast.LENGTH_LONG).show();

				tv3.setText("Second File Contents :" + readFromSD(path2));

			}
		});

	}

	public static boolean copyFile(String from, String to) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(from);
			if (oldfile.exists()) {
				InputStream inStream = new FileInputStream(from);
				FileOutputStream fs = new FileOutputStream(to);
				byte[] buffer = new byte[1444];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread;
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
				fs.close();
			}
			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return false;
		}
	}

	public String readFromSD(String path) {
		File file = new File(path);
		StringBuilder text = new StringBuilder();
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));
			String line;
			while ((line = br.readLine()) != null) {
				text.append(line);
				text.append('\n');
			}
		} catch (IOException e) {
		}
		return text.toString();
	}

}

Note : if you are writing to Sdcard, then always give this permission in the AndroidManifest file.

  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Another important thing is here I am not creating the file to copy, simply assuming that the first file is present in the sdcard in the correct path.

Copy File

Copy File

Download complete Android source code from here.

Download the tutorial PDF from here.

Leave a Reply

Your email address will not be published. Required fields are marked *