The Different Ways You Can Copy Files in Java

Try one of these approaches to copying a file in Java, but be sure to understand which is best for your needs.

A few scenarios require you to copy a file in Java. You may be creating a simple script to automate processes for a file manager. You could even be writing a full-blown application that works with files.

There are many ways that you can copy a file, depending on your required performance, simplicity, or even what Java version you are using.

How to Copy Files Using FileInputStream and FileOutputStream

This method works by manually reading each byte of data from the file, and writing it to a new destination. Unlike the Files.copy method below, you can use this method for all Java versions, including Java 6 and prior.

It uses the FileInputStream class to read bytes from a source file, and the FileOutputStream to write bytes to the destination.

  1. Create a file anywhere on your computer called “SimpleScript.java”.
  2. Open the file in a text editor or IDE, and copy the following base code to the application.

    import

    java.io.IOException;\n \nclass SimpleScript { \

    n

    public

    static

    void

    main

    (String args[])

    throws

    IOException { \n

  3. Import these additional Input Stream and Output Stream classes at the top of the file, just after the first import statement.

    import

    java.io.File;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;

  4. Create a new file called “Copy-File-1.txt”, in the same folder as your SimpleScript.java file. Add any written content inside the file.
  5. In the same folder, also create a new directory called “Destination”. The goal is to copy the “Copy-File-1.txt” file into the new folder.
  6. Inside the main function of the class, use the File class to create two new file objects. The source, which will be the file you want to copy, and the destination, which will be where you want to copy the file to. If the destination file doesn’t exist, your program will create a new one.

    class

    SimpleScript

    { \

    n

    public

    static

    void

    main

    (String args[])

    throws

    IOException { \n

  7. After that, create an InputStream and OutputStream object. InputStream input =

    null

    ;\nOutputStream output =

    null

    ;

  8. Use the input stream to read the data in bytes, and the output stream to write the data to the new location.

    try

    {\n

  9. To run the script, open a command line. Navigate to the folder where you stored your Java file using the cd command on the Windows Command Prompt or the Mac Terminal.

    cd

    Desktop

  10. To compile the script, save the Java file and run the Javac command in the command line: javac SimpleScript.java
  11. To run the script, use the Java command: java SimpleScript You should see a single line of output with no errors: Java commands to run the script in the console
  12. Navigate to your “Destination” folder to view your copied file. Location of destination file after copying
  13. Open the file to view the content, which your program copied from the original file. Text file with content copied from the original file

How to Copy Files Using Files.copy

If you are using Java 7 or later, you can use the Files.copy method. This method is generally a simpler implementation. According to the Java Documentation, there are multiple overloads for the function.

For example, the Files.copy method can also use an input stream to copy files from one location to another, but through a method using less code. You can also use Paths, or specify yourself how you want the method to copy your file.

  1. Create a new file called “Copy-File-2.txt”, in the same folder as your SimpleScript.java file. Add any written content inside the file.
  2. At the top of the file, add imports for the “java.nio.file.Paths” and “java.nio.file.Files” classes.

    import

    java.nio.file.Paths;\nimport java.nio.file.Files;

  3. Add two strings, representing the relative file path for the source file and the destination. Use the Files.copy method, which will already handle the logic to copy the file to the destination. String copySource = "Copy-File-

    2

    .txt";\nString copyDestination = "Destination/Copy-File-

    2

    .txt";\n \ntry {\n Files.copy(Paths.get(copySource), Paths.get(copyDestination));\n}

    catch

    (Exception e) {\n System.out.println("Could not copy the file to the destination: " + copyDestination + ". Check

    if

    the folder or file already exists.");\n}\nSystem.out.println("

    2

    nd File copied");

  4. Run the script using the Javac and Java commands.
  5. Navigate to your “Destination” folder to view your copied file. Second copied file

How to Copy Files Using FileChannel.transferTo()

According to the Java Documentation, this method can be a potentially faster way to copy files. However, this will depend on the way you implement the function.

  1. Create a new file called “Copy-File-3.txt”, in the same folder as your SimpleScript.java file. Add some sample content to this file.
  2. At the top of SimpleScript.java, import the “java.nio.channels.FileChannel” class alongside three of the previous common file-related classes from the io package.

    import

    java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.nio.channels.FileChannel;

  3. Create file objects for the source and destination, and use those to create an Input Stream and an Output Stream. File src =

    new

    File("Copy-File-

    3

    .txt");\nFile dst =

    new

    File("Destination/Copy-File-

    3

    .txt");\nFileInputStream inStream =

    new

    FileInputStream(src);\nFileOutputStream outStream =

    new

    FileOutputStream(dst);

  4. Use the TransferTo method from the FileChannel class to copy the file to its destination.

    try

    {\n FileChannel inChannel = inStream.getChannel();\n FileChannel outChannel = outStream.getChannel();\n inChannel.transferTo(

    0

    , inChannel.size(), outChannel);\n}

    catch

    (Exception e) {\n System.out.println("Could not copy the file to the destination: " + dst.getPath() + ". Check

    if

    the folder or file already exists.");\n}

    finally

    {\n

  5. Run the script using the Javac and Java commands.
  6. Navigate to your “Destination” folder to view your copied file. Third Copied File

Copying Files in Java Is Just the Start

There are many ways that you can copy a file in Java. Three possible ways include using the traditional stream method, the Files.copy method, or the transferTo method.

There are many other file manager operations you can perform using Java. Some of these include moving files, deleting files, or zipping files. These can be useful to learn if you need to automate certain processes in the file manager.