0

I need to copy file from one place to another. I have found good solution :

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileCopyTest {
public static void main(String[] args) {
    Path source = Paths.get("/Users/apple/Desktop/test.rtf");
    Path destination = Paths.get("/Users/apple/Desktop/copied.rtf");

    try {
        Files.copy(source, destination);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

This library work good, but in doesn't available in Android...

I try figure out which way i should use instead of, but it any suggestion... I am almost sure that it should be a library which allow copy files in one go.

If someone know say please, i am sure it will be very helpful answer for loads of people.

Thanks!

Sirop4ik
  • 4,543
  • 2
  • 54
  • 121
  • Possible duplicate of [How to programmatically move, copy and delete files and directories on SD?](http://stackoverflow.com/questions/4178168/how-to-programmatically-move-copy-and-delete-files-and-directories-on-sd) – Mike M. May 02 '16 at 08:50
  • If you only want links to a library to do this for you, then this is not an appropriate question for Stack Overflow. – Mike M. May 02 '16 at 08:51
  • @MikeM. i edit the header – Sirop4ik May 02 '16 at 08:59

3 Answers3

0

try this code

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class CopyFile {

public static void main(String[] args) {
    File sourceFile = new File(
            "/Users/Neel/Documents/Workspace/file1.txt");

    File destFile = new File(
            "/Users/Neel/Documents/Workspace/file2.txt");

    /* verify whether file exist in source location */
    if (!sourceFile.exists()) {
        System.out.println("Source File Not Found!");
    }

    /* if file not exist then create one */
    if (!destFile.exists()) {
        try {
            destFile.createNewFile();

            System.out.println("Destination file doesn't exist. Creating   

     one!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    FileChannel source = null;
    FileChannel destination = null;

    try {

        /**
         * getChannel() returns unique FileChannel object associated a file
         * output stream.
         */
        source = new FileInputStream(sourceFile).getChannel();

        destination = new FileOutputStream(destFile).getChannel();

        if (destination != null && source != null) {
            destination.transferFrom(source, 0, source.size());
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    finally {
        if (source != null) {
            try {
                source.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (destination != null) {
            try {
                destination.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    }
    }
Damini Mehra
  • 3,257
  • 3
  • 13
  • 24
0

Well with commons-io, you can do this

FileInputStream source = null;
FileOutputStream destination = null;
try {
    source = new FileInputStream(new File(/*...*/));
    destination = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), /*...*/);
    IOUtils.copy(source, destination);
} finally {
    IOUtils.closeQuietly(source);
    IOUtils.closeQuietly(destination);
}

Just add

compile 'org.apache.directory.studio:org.apache.commons.io:2.4' 

to the build.gradle file

Sirop4ik
  • 4,543
  • 2
  • 54
  • 121
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • What do you mean **not available in Android** ? Add it to your build.gradle dependencies. If you want to use the default classes available and apparently NOT a library despite what you claimed in your initial post, then just do what `commons-io` would do if you included it. – EpicPandaForce May 02 '16 at 11:21
  • Although please note that writing to `Environment.getExternalStorageDirectory()` requires runtime permission since Android 6.0+ – EpicPandaForce May 03 '17 at 15:13
-1

Use this utility class to read/write file in sdcard:

public class MyFile {

    String TAG = "MyFile";
    Context context;
    public MyFile(Context context){
        this.context = context;
    }

    public Boolean writeToSD(String text){
        Boolean write_successful = false;
         File root=null;  
            try {  
                // check for SDcard   
                root = Environment.getExternalStorageDirectory();  
                Log.i(TAG,"path.." +root.getAbsolutePath());  

                //check sdcard permission  
                if (root.canWrite()){  
                    File fileDir = new File(root.getAbsolutePath());  
                    fileDir.mkdirs();  

                    File file= new File(fileDir, "samplefile.txt");  
                    FileWriter filewriter = new FileWriter(file);  
                    BufferedWriter out = new BufferedWriter(filewriter);  
                    out.write(text);  
                    out.close();  
                    write_successful = true;
                }  
            } catch (IOException e) {  
                Log.e("ERROR:---", "Could not write file to SDCard" + e.getMessage());  
                write_successful = false;
            }  
        return write_successful;
    }

    public String readFromSD(){
        File sdcard = Environment.getExternalStorageDirectory();
        File file = new File(sdcard,"samplefile.txt");
        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();
    }

    @SuppressLint("WorldReadableFiles")
    @SuppressWarnings("static-access")
    public Boolean writeToSandBox(String text){
        Boolean write_successful = false;
        try{
            FileOutputStream fOut = context.openFileOutput("samplefile.txt",
                    context.MODE_WORLD_READABLE);
            OutputStreamWriter osw = new OutputStreamWriter(fOut); 
            osw.write(text);
            osw.flush();
            osw.close();
        }catch(Exception e){
            write_successful = false;
        }
        return write_successful;
    }
    public String readFromSandBox(){
        String str ="";
        String new_str = "";
        try{
            FileInputStream fIn = context.openFileInput("samplefile.txt");
            InputStreamReader isr = new InputStreamReader(fIn);
            BufferedReader br=new BufferedReader(isr);

            while((str=br.readLine())!=null)
            {
                new_str +=str;
                System.out.println(new_str);
            }            
        }catch(Exception e)
        {           
        }
        return new_str;
    }
}

Note you should give this permission in the AndroidManifest file.

Here permision

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" 

For more details visit : http://www.coderzheaven.com/2012/09/06/read-write-files-sdcard-application-sandbox-android-complete-example/

Android developer official Docs

Sirop4ik
  • 4,543
  • 2
  • 54
  • 121
USKMobility
  • 5,721
  • 2
  • 27
  • 34