Search code examples
javaandroidandroid-sdcardoverwritecopying

How to make a button write a file to sdcard?


In my app I want a button which when pressed copies a file stored in my apps raw folder to sdcard/Android/data... overwriting an existing file that is already there.

Here is what I have so far. The file in my raw folder is called brawler.dat for an example.

I'm not asking anyone to write the entire code, but that would be a bonus for sure.

I need mainly someone to point me in the right direction.

I can create buttons to go to URL's etc... but I'm ready for the next level, I feel.

main.xml

 rLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Overwrite File" />

FreelineActivity.java

     package my.freeline.conquest;

import android.app.Activity;
import android.os.Bundle;

public class FreelineActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

Solution

  • You can do the following simple call the copyRawFile().For more details on storage refer to http://developer.android.com/guide/topics/data/data-storage.html

        private void copyRawFile() {
    
    
                    InputStream in = null;
                    OutputStream out = null;
        String filename="myFile"; //sd card file name           
        try {
    //Provide the id of raw file to the openRawResource() method
                      in = getResources().openRawResource(R.raw.brawler);
                      out = new FileOutputStream("/sdcard/" + filename);
                      copyFile(in, out);
                      in.close();
                      in = null;
                      out.flush();
                      out.close();
                      out = null;
                    } catch(Exception e) {
                        Log.e("tag", e.getMessage());
                    }       
    
            }
            private void copyFile(InputStream in, OutputStream out) throws IOException {
                byte[] buffer = new byte[1024];
                int read;
                while((read = in.read(buffer)) != -1){
                  out.write(buffer, 0, read);
                }
            }