88

I want to copy a file from one location to another location in Java. What is the best way to do this?


Here is what I have so far:

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
public class TestArrayList {
    public static void main(String[] args) {
        File f = new File(
            "D:\\CBSE_Demo\\Demo_original\\fscommand\\contentplayer\\config");
        List<String>temp=new ArrayList<String>();
        temp.add(0, "N33");
        temp.add(1, "N1417");
        temp.add(2, "N331");
        File[] matchingFiles = null;
        for(final String temp1: temp){
            matchingFiles = f.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.startsWith(temp1);
                }
            });
            System.out.println("size>>--"+matchingFiles.length);

        }
    }
}

This does not copy the file, what is the best way to do this?

Raedwald
  • 46,613
  • 43
  • 151
  • 237
vijayk
  • 2,633
  • 14
  • 38
  • 59
  • 2
    Start with [Basic I/O](http://docs.oracle.com/javase/tutorial/essential/io/) and also try having a look at [Copying a File or Directory](http://docs.oracle.com/javase/tutorial/essential/io/copy.html) – MadProgrammer May 08 '13 at 06:20
  • My first problem is how to store that search files ? – vijayk May 08 '13 at 06:23
  • I'm not sure why you would need, however, take a look at [Collections](http://docs.oracle.com/javase/tutorial/collections/TOC.html), I'd focus somewhere around `List` – MadProgrammer May 08 '13 at 06:25
  • Possible duplicate of [Copying files from one directory to another in Java](http://stackoverflow.com/questions/1146153/copying-files-from-one-directory-to-another-in-java) – demongolem May 10 '17 at 15:49

9 Answers9

150

You can use this (or any variant):

Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);

Also, I'd recommend using File.separator or / instead of \\ to make it compliant across multiple OS, question/answer on this available here.

Since you're not sure how to temporarily store files, take a look at ArrayList:

List<File> files = new ArrayList();
files.add(foundFile);

To move a List of files into a single directory:

List<File> files = ...;
String path = "C:/destination/";
for(File file : files) {
    Files.copy(file.toPath(),
        (new File(path + file.getName())).toPath(),
        StandardCopyOption.REPLACE_EXISTING);
}
Community
  • 1
  • 1
Menno
  • 12,175
  • 14
  • 56
  • 88
  • 1
    Files class is available since JDK 1.7..http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html – Jaydeep Rajput May 08 '13 at 06:24
  • this is only used when you want to copy whole folder from one location to another .But I want to search first and then copy that only search folders. – vijayk May 08 '13 at 06:25
  • In case your `Path` object references a file (say `C:\\mytext.txt`), if copies the file. Ofcourse similar options are available to simply `move` the file (as documented in the given link). As Jai correctly mentioned, make sure you are using JDK 1.7. Otherwise there are other options ofcourse. – Menno May 08 '13 at 06:27
  • 1
    @vijayk If you took the time to read the links I suggested you would have found a number of useful ideas, like [Walking the File Tree](http://docs.oracle.com/javase/tutorial/essential/io/walk.html)... – MadProgrammer May 08 '13 at 06:28
  • 1
    +1 for Files.copy but I dont agree about File.separator, File normalizes the path anyway, so back or forward slash makes no difference. – Evgeniy Dorofeev May 08 '13 at 06:29
  • @EvgeniyDorofeev: You're right. Though in that case OP would be better of using `/` instead of `\\` (as per [this question/answer](http://stackoverflow.com/questions/2417485/file-separator-vs-slash-in-paths)) – Menno May 08 '13 at 06:32
  • @Aquillo :I used same arraylist concept but I cant add that search file. In my code I used File[] matchingFiles; Can you please tell me how to add those type of object in ArrayList? – vijayk May 08 '13 at 06:35
  • 1
    @vijayk: You are using an `ArrayList` to store `String`s which won't work. You are also using an `array` to store files, though remember this is a fixed size and you cannot **append** to an array, only use available keys (e.g. `myFileArray[0] = new File("");`). – Menno May 08 '13 at 06:37
  • Though for searching files, I'd recommend taking a look at MadProgrammer's examples. No need to reinvent the wheel, right? :) – Menno May 08 '13 at 06:38
  • @Aquillo: Suppose I have list of folders which I want to copy . eg.List files = new ArrayList(); files object content all files then how to copy to :D\\ISCE_Demo\\ location? – vijayk May 08 '13 at 06:51
  • 1
    @vijayk I've extended my answer. – Menno May 08 '13 at 07:37
  • @Aquillo: this code only create folders name not copy the content between that folder. – vijayk May 08 '13 at 10:19
  • Try debugging and take a look at the two `Path`s passed to Files.copy(). – Menno May 08 '13 at 10:20
  • This method is working for me properly, But, After some time, the application starts throwing "Too many files open" error when I try to invoke this method. – Shivanshu Goyal Oct 11 '19 at 06:17
88

Update:

see also https://stackoverflow.com/a/67179064/1847899

Using Stream

private static void copyFileUsingStream(File source, File dest) throws IOException {
    InputStream is = null;
    OutputStream os = null;
    try {
        is = new FileInputStream(source);
        os = new FileOutputStream(dest);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }
    } finally {
        is.close();
        os.close();
    }
}

Using Channel

private static void copyFileUsingChannel(File source, File dest) throws IOException {
    FileChannel sourceChannel = null;
    FileChannel destChannel = null;
    try {
        sourceChannel = new FileInputStream(source).getChannel();
        destChannel = new FileOutputStream(dest).getChannel();
        destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
       }finally{
           sourceChannel.close();
           destChannel.close();
       }
}

Using Apache Commons IO lib:

private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
    FileUtils.copyFile(source, dest);
}

Using Java SE 7 Files class:

private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
    Files.copy(source.toPath(), dest.toPath());
}

Or try Googles Guava :

https://github.com/google/guava

docs: https://guava.dev/releases/snapshot-jre/api/docs/com/google/common/io/Files.html

Alexander Sidikov Pfeif
  • 2,418
  • 1
  • 20
  • 35
  • 1
    Thanks, Apache Commons FileUtils saved my life, since I needed to build old Java 6 project where nio packages are not available. `FileUtils.copyFile(...)` is even shorter/handy than nio `Files.copy(...)` due to no need of converting the files to Path. – RAM237 Sep 01 '17 at 22:43
  • 1
    you can try Googles guava lib also... watch out some Version doesnt support Java 6 .. i will update my post next days – Alexander Sidikov Pfeif Sep 03 '17 at 17:31
10

Use the New Java File classes in Java >=7.

Create the below method and import the necessary libs.

public static void copyFile( File from, File to ) throws IOException {
    Files.copy( from.toPath(), to.toPath() );
} 

Use the created method as below within main:

File dirFrom = new File(fileFrom);
File dirTo = new File(fileTo);

try {
        copyFile(dirFrom, dirTo);
} catch (IOException ex) {
        Logger.getLogger(TestJava8.class.getName()).log(Level.SEVERE, null, ex);
}

NB:- fileFrom is the file that you want to copy to a new file fileTo in a different folder.

Credits - @Scott: Standard concise way to copy a file in Java?

Community
  • 1
  • 1
Amimo Benja
  • 505
  • 5
  • 8
5
  public static void copyFile(File oldLocation, File newLocation) throws IOException {
        if ( oldLocation.exists( )) {
            BufferedInputStream  reader = new BufferedInputStream( new FileInputStream(oldLocation) );
            BufferedOutputStream  writer = new BufferedOutputStream( new FileOutputStream(newLocation, false));
            try {
                byte[]  buff = new byte[8192];
                int numChars;
                while ( (numChars = reader.read(  buff, 0, buff.length ) ) != -1) {
                    writer.write( buff, 0, numChars );
                }
            } catch( IOException ex ) {
                throw new IOException("IOException when transferring " + oldLocation.getPath() + " to " + newLocation.getPath());
            } finally {
                try {
                    if ( reader != null ){                      
                        writer.close();
                        reader.close();
                    }
                } catch( IOException ex ){
                    Log.e(TAG, "Error closing files when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() ); 
                }
            }
        } else {
            throw new IOException("Old location does not exist when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
        }
    }  
Quamber Ali
  • 2,170
  • 25
  • 46
2

Copy a file from one location to another location means,need to copy the whole content to another location.Files.copy(Path source, Path target, CopyOption... options) throws IOException this method expects source location which is original file location and target location which is a new folder location with destination same type file(as original). Either Target location needs to exist in our system otherwise we need to create a folder location and then in that folder location we need to create a file with the same name as original filename.Then using copy function we can easily copy a file from one location to other.

 public static void main(String[] args) throws IOException {
                String destFolderPath = "D:/TestFile/abc";
                String fileName = "pqr.xlsx";
                String sourceFilePath= "D:/TestFile/xyz.xlsx";
                File f = new File(destFolderPath);
                if(f.mkdir()){
                    System.out.println("Directory created!!!!");
                }
                else {
                    System.out.println("Directory Exists!!!!");
                }
                f= new File(destFolderPath,fileName);
                if(f.createNewFile())   {

                    System.out.println("File Created!!!!");
                }   else {
                    System.out.println("File exists!!!!");
                }

                Files.copy(Paths.get(sourceFilePath), Paths.get(destFolderPath, fileName),REPLACE_EXISTING);
                System.out.println("Copy done!!!!!!!!!!!!!!");


            }
S.Sarkar
  • 59
  • 5
  • I agree with you on a specific point. Where I see in most of the answers they are using the same directory. I was expecting to see them using a different source(directory) and different destination(directory). – Dlaw Feb 08 '22 at 10:09
2

You can do it with the Java 8 Streaming API, PrintWriter and the Files API

try (PrintWriter pw = new PrintWriter(new File("destination-path"), StandardCharsets.UTF_8)) {
    Files.readAllLines(Path.of("src/test/resources/source-file.something"), StandardCharsets.UTF_8)
         .forEach(pw::println);
}

If you want to modify the content on-the-fly while copying, check out this link for the extended example https://overflowed.dev/blog/copy-file-and-modify-with-java-streams/

Marian Klühspies
  • 15,824
  • 16
  • 93
  • 136
1

I modified one of the answers to make it a bit more efficient.

public void copy(){
    InputStream in = null;
    try {
        in = new FileInputStream(Files);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    try {
        OutputStream out = new FileOutputStream();
        try {
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            while (true) {
                int len = 0;
                try {
                    if (!((len = in.read(buf)) > 0)) break;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    out.write(buf, 0, len);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

private void moveFile() {
    copy();
    File dir = getFilesDir();
    File file = new File(dir, "my_filename");
    boolean deleted = file.delete();
}
0

Files.exists()

Files.createDirectory()

Files.copy()

Overwriting Existing Files: Files.move()

Files.delete()

Files.walkFileTree() enter link description here

Shinwar ismail
  • 299
  • 2
  • 9
-1

You can use

FileUtils.copy(sourceFile, destinationFile);

https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html

Pavan
  • 543
  • 4
  • 16