Copy files using the copy() method of the Files class
In Java,Classic
copy()
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 pathsourceFilePath
and target file pathtargetFilePath
。
2) CreatePath
Object:use()
Methods are created based on file pathPath
Object.
3) Copy the file: Called()
Method copy the source file to the destination path.
4) Exception handling:usetry-catch
Block capture and process possible occurrencesIOException
abnormal.
Overwrite existing target files
If the target file already exists,()
The method will be thrownFileAlreadyExistsException
abnormal.
If you want to overwrite the existing target file, you can use itStandardCopyOption.REPLACE_EXISTING
Options.
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_EXISTING
The 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.