SoFunction
Updated on 2025-05-07

Use FileChannel to copy and move files

In Java,FileChannelyesA powerful tool in the package that can be used for read and write files, and it can efficiently copy and move files.

Here is a detailed introduction to how to use itFileChannelImplement these two functions:

Use FileChannel to copy files

With the helpFileChanneloftransferFrom()ortransferTo()The method can efficiently transfer data between channels, thereby enabling file copying.

import ;
import ;
import ;
import ;

public class FileCopyWithFileChannel {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("");
             FileOutputStream fos = new FileOutputStream("");
             FileChannel sourceChannel = ();
             FileChannel targetChannel = ()) {

            // Use transferFrom method to copy the file            (sourceChannel, 0, ());
            ("File copy successfully");
        } catch (IOException e) {
            ("File copy failed: " + ());
        }
    }
}    

Code explanation

1. Create input and output streams and channels

  • FileInputStreamUsed to read source files,FileOutputStreamUsed to write to the target file.
  • passgetChannel()Methods to obtain source and target files respectivelyFileChannelObject.

2. UsetransferFrom()Method Copy File

  • transferFrom()Method transfers data from the source channel to the target channel.
  • The first parameter is the source channel, the second parameter is the starting position of the target channel, and the third parameter is the number of bytes to be transferred.

3. Exception handling

  • usetry-with-resourcesStatement ensures that the resource is automatically closed
  • Capture and process possible occurrences simultaneouslyIOExceptionabnormal

Use FileChannel to enable file movement

File movement essentially means copying the file first and then deleting the source file.

import ;
import ;
import ;
import ;
import ;

public class FileMoveWithFileChannel {
    public static void main(String[] args) {
        File sourceFile = new File("");
        File targetFile = new File("");

        try (FileInputStream fis = new FileInputStream(sourceFile);
             FileOutputStream fos = new FileOutputStream(targetFile);
             FileChannel sourceChannel = ();
             FileChannel targetChannel = ()) {

            // Use transferFrom method to copy the file            (sourceChannel, 0, ());

            // Delete the source file            if (()) {
                ("File moves successfully");
            } else {
                ("Source file deletion failed");
            }
        } catch (IOException e) {
            ("File Movement Failed: " + ());
        }
    }
}

Code explanation

1) Create file objects and channels:createFileThe object represents the source file and the target file, and then creates the input and output stream and the correspondingFileChannelObject.

2) Copy the file:usetransferFrom()Method copy the data from the source file to the target file.

3) Delete the source file: CalledFileThe object'sdelete()Method delete the source file and determine whether it is successfully deleted based on the returned result.

4) Exception handling:usetry-with-resourcesStatements ensure that the resource is automatically closed, while capturing and processing possible occurrencesIOExceptionabnormal.

Things to note

Need to""and""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.