SoFunction
Updated on 2025-05-19

Use the copy method of the Files class in Java to copy files

Copy files using the copy() method of the Files class

In Java,Classiccopy()Methods can be used to copy files or directories.

The following provides you with the usecopy()Sample code for method copying files:

Simple file copy example

The following code copies a file from the source path to the destination path.

import ;
import ;
import ;
import ;

public class FileCopyExample {
    public static void main(String[] args) {
        // Source file path        String sourceFilePath = "path/to/source/";
        // Target file path        String targetFilePath = "path/to/target/";

        Path sourcePath = (sourceFilePath);
        Path targetPath = (targetFilePath);

        try {
            // Copy the file            (sourcePath, targetPath);
            ("File copy successfully");
        } catch (IOException e) {
            ("File copy failed: " + ());
        }
    }
}    

Code explanation

1) Specify the path: Define the source file pathsourceFilePathand target file pathtargetFilePath

2) CreatePath Object:use()Methods are created based on file pathPathObject.

3) Copy the file: Called()Method copy the source file to the destination path.

4) Exception handling:usetry-catchBlock capture and process possible occurrencesIOExceptionabnormal.

Overwrite existing target files

If the target file already exists,()The method will be thrownFileAlreadyExistsExceptionabnormal.

If you want to overwrite the existing target file, you can use itStandardCopyOption.REPLACE_EXISTINGOptions.

import ;
import ;
import ;
import ;
import ;

public class FileCopyWithReplace {
    public static void main(String[] args) {
        String sourceFilePath = "path/to/source/";
        String targetFilePath = "path/to/target/";

        Path sourcePath = (sourceFilePath);
        Path targetPath = (targetFilePath);

        try {
            (sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
            ("File copy successfully (overwrite existing files)");
        } catch (IOException e) {
            ("File copy failed: " + ());
        }
    }
}

In this example,StandardCopyOption.REPLACE_EXISTINGThe option is passed as the third parameter to()Method, which indicates that the target file will be overwritten if it already exists.

You need to"path/to/source/"and"path/to/target/"Replace with the actual file path.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.