Display Word
Display Word

Reputation: 106

How to copy a file in Java

I'm using Android Studio. Is there a possible command that will copy say, a picture in your DCIM folder and moves it to the root directory of the SD card? I have researched around and I have found nothing. I have decompiled other apps and found nothing. As you can probably tell I am a beginner to average programer. I just began Java for this project.

Even if there is not I would like to know so I can stop racking the web for answers :P

Thanks, All comments welcome, Will post more info If needed! :)

Upvotes: 1

Views: 3977

Answers (2)

Sunny Shah
Sunny Shah

Reputation: 928

To copy file you can use following:

File fileToCopy = new File("path to file you want to copy");
File destinationFile = new File(Environment.getExternalStorageDirectory(),"filename");

FileInputStream fis = new FileInputStream(fileToCopy);
FileOutputStream fos = new FileOutputStream(destinationFile);

byte[] b = new byte[1024];
int noOfBytesRead;

while((noOfBytesRead = fis.read(b)) != -1)
     fos.write(b,0,noOfBytesRead);
fis.close();
fos.close();

Upvotes: 2

Darshil Shah
Darshil Shah

Reputation: 361

Use this function

public void copyFile(File sourceFile, File destFile)
            throws IOException {

        if (!destFile.exists()) {
            destFile.createNewFile();
        }

        FileChannel source = null;
        FileChannel destination = null;
        FileInputStream is = null;
        FileOutputStream os = null;
        try {
            is = new FileInputStream(sourceFile);
            os = new FileOutputStream(destFile);
            source = is.getChannel();
            destination = os.getChannel();

            long count = 0;
            long size = source.size();
            while ((count += destination.transferFrom(source, count, size
                    - count)) < size)
                ;
        } catch (Exception ex) {
        } finally {
            if (source != null) {
                source.close();
            }
            if (is != null) {
                is.close();
            }
            if (destination != null) {
                destination.close();
            }
            if (os != null) {
                os.close();
            }
        }
    }

Upvotes: 3

Related Questions