Craft

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;

    class SimpleScript {
    public static void main(String args[]) throws IOException {
    }
    }

  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;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.FileInputStream;
    import 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 {    
    public static void main(String args[]) throws IOException {
    File source = new File("Copy-File-1.txt");
    File destination = new File("Destination/Copy-File-1.txt");
    }
    }
  7. After that, create an InputStream and OutputStream object.
    InputStream input = null;
    OutputStream 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 {
    input = new FileInputStream(source);
    output = new FileOutputStream(destination);
    byte[] buf = new byte[1024];
    int bytesRead;


    while ((bytesRead = input.read(buf)) > 0) {
    output.write(buf, 0, bytesRead);
    }
    } catch (IOException e) {
    e.printStackTrace();
    System.out.println("Could not copy the file to the destination: " + destination.getPath() + ". Check if the folder or file already exists.");
    } finally {
    if (input != null) {
    input.close();
    }

    if (output != null) {
    output.close();
    }
    }

    System.out.println("File copied");

  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:

  12. Navigate to your “Destination” folder to view your copied file.
  13. Open the file to view the content, which your program 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;
    import 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";
    String copyDestination = "Destination/Copy-File-2.txt";

    try {
    Files.copy(Paths.get(copySource), Paths.get(copyDestination));
    } catch (Exception e) {
    System.out.println("Could not copy the file to the destination: " + copyDestination + ". Check if the folder or file already exists.");
    }
    System.out.println("2nd File copied");

  4. Run the script using the Javac and Java commands.
  5. Navigate to your “Destination” folder to view your 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;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import 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");
    File dst = new File("Destination/Copy-File-3.txt");
    FileInputStream inStream = new FileInputStream(src);
    FileOutputStream outStream = new FileOutputStream(dst);
  4. Use the TransferTo method from the FileChannel class to copy the file to its destination.
    try {
    FileChannel inChannel = inStream.getChannel();
    FileChannel outChannel = outStream.getChannel();
    inChannel.transferTo(0, inChannel.size(), outChannel);
    } catch (Exception e) {
    System.out.println("Could not copy the file to the destination: " + dst.getPath() + ". Check if the folder or file already exists.");
    } finally {
    inStream.close();
    outStream.close();
    }
    System.out.println("3rd File copied");
  5. Run the script using the Javac and Java commands.
  6. Navigate to your “Destination” folder to view your 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.

Read the full article here

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button