📜  在Java复制文件的不同方法

📅  最后修改于: 2022-05-13 01:54:35.811000             🧑  作者: Mango

在Java复制文件的不同方法

使用Java语言复制文件主要有3种方式。它们如下所示:

  1. 使用文件流(Naive 方法)
  2. 使用 FileChannel 类
  3. 使用 Files 类。

注意:还有许多其他方法,例如 Apache Commons IO FileUtils,但我们仅讨论使用Java类复制文件。

方法一:使用文件流(Naive方法)

这是一种简单的方法,我们使用文件输入流从第一个文件中获取输入字符,并使用文件输出流将输出字符写入另一个文件。这就像看到一个文件并写入另一个文件一样。

例子:



Java
// Java Program to Copy file using File Stream
 
// Importing input output classes
import java.io.*;
 
// Main Class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
        throws IOException
    {
 
        // Creating two stream
        // one input and other output
        FileInputStream fis = null;
        FileOutputStream fos = null;
 
        // Try block to check for exceptions
        try {
 
            // Initializing both the streams with
            // respective file directory on local machine
 
            // Custom directory path on local machine
            fis = new FileInputStream(
                "C:\\Users\\Dipak\\Desktop\\input.txt");
 
            // Custom directory path on local machine
            fos = new FileOutputStream(
                "C:\\Users\\Dipak\\Desktop\\output.txt");
 
            int c;
 
            // Condition check
            // Reading the input file till there is input
            // present
            while ((c = fis.read()) != -1) {
 
                // Writing to output file of the specified
                // directory
                fos.write(c);
            }
 
            // By now writing to the file has ended, so
 
            // Display message on the console
            System.out.println(
                "copied the file successfully");
        }
 
        // Optional finally keyword but is good practice to
        // empty the occupied space is recommended whenever
        // closing files,connections,streams
        finally {
 
            // Closing the streams
 
            if (fis != null) {
 
                // Closing the fileInputStream
                fis.close();
            }
            if (fos != null) {
 
                // Closing the fileOutputStream
                fos.close();
            }
        }
    }
}


Java
// Java Program to Copy Files Using FileChannel Class
 
// Importing java.nio package for network linking
// Importing input output classes
import java.io.*;
import java.nio.channels.FileChannel;
 
// Main Class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
        throws IOException
    {
 
        // Creating two channels one input and other output
        // by creating two objects of FileChannel Class
        FileChannel src
            = new FileInputStream(
                  "C:\\Users\\Dipak\\Desktop\\input.txt")
                  .getChannel();
        FileChannel dest
            = new FileOutputStream(
                  "C:\\Users\\Dipak\\Desktop\\output.txt")
                  .getChannel();
 
        // Try block to check for exceptions
        try {
 
            // Transfering files in one go from source to
            // destination using transferFrom() method
            dest.transferFrom(src, 0, src.size());
            // we can also use transferTo
            // src.transferTo(0,src.size(),dest);
        }
 
        // finally keyword is good practice to save space in
        // memory by closing files, connections, streams
        finally {
 
            // Closing the channels this makes the space
            // free
 
            // Closing the source channel
            src.close();
 
            // Closing the destination channel
            dest.close();
        }
    }
}


Java
import java.nio.file.Files;
import java.io.*;
// save the file named as GFG.java
public class GFG{
   
    // main method
    public static void main(String[] args) throws IOException{
       
        // creating two channels
        // one input and other output   
        File src = new File("C:\\Users\\Dipak\\Desktop\\input.txt");
        File dest = new File("C:\\Users\\Dipak\\Desktop\\output.txt");
             
        // using copy(InputStream,Path Target); method
        Files.copy(src.toPath(), dest.toPath());
       
        // here we are not required to have an
        // output file at the specified target.
        // same way we can use other method also.
             
    }
}



输出:

copied the file successfully 

对于上面的程序,我们需要一个 input.txt 和一个 output.txt 文件。最初,两个文本文件看起来像这样



程序执行成功后,

方法 2:使用 FileChannel 类

这是Java.nio 中的一个类,channels 包,用于写入、修改、读取文件。此类的对象创建了一个可查找的 fie 通道,通过该通道执行所有这些活动。这个类基本上提供了两个命名如下的方法:

  • transferFrom(ReadableByteChannel src, long position, long count):将字节传输到从 src 通道调用此方法的通道。这由目标通道调用。该位置是一个指针的位置,从那里开始复制操作。 Count 指定文件的大小,它几乎等于它包含的内容量。
  • transferTo(long position, long count, WritableByteChannel target) :将字节从源或方法调用通道传输到文件的目标通道。此方法主要使用源通道调用,Count 提到源文件的大小和要进行复制的位置



因此,我们可以使用这两种方法中的任何一种来传输文件数据并复制它们。

例子:

Java

// Java Program to Copy Files Using FileChannel Class
 
// Importing java.nio package for network linking
// Importing input output classes
import java.io.*;
import java.nio.channels.FileChannel;
 
// Main Class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
        throws IOException
    {
 
        // Creating two channels one input and other output
        // by creating two objects of FileChannel Class
        FileChannel src
            = new FileInputStream(
                  "C:\\Users\\Dipak\\Desktop\\input.txt")
                  .getChannel();
        FileChannel dest
            = new FileOutputStream(
                  "C:\\Users\\Dipak\\Desktop\\output.txt")
                  .getChannel();
 
        // Try block to check for exceptions
        try {
 
            // Transfering files in one go from source to
            // destination using transferFrom() method
            dest.transferFrom(src, 0, src.size());
            // we can also use transferTo
            // src.transferTo(0,src.size(),dest);
        }
 
        // finally keyword is good practice to save space in
        // memory by closing files, connections, streams
        finally {
 
            // Closing the channels this makes the space
            // free
 
            // Closing the source channel
            src.close();
 
            // Closing the destination channel
            dest.close();
        }
    }
}


输出:

对于上面的程序,我们需要一个 input.txt 和一个 output.txt 文件。最初,两个文本文件看起来像这样



程序执行成功后,

方法 3:使用 Files 类

这是Java.nio.File包中的一个类。该类提供了3种方法来复制文件,如下所示:

  • copy(InputStream in, Path target):将输入文件流中的所有数据字节复制到输出文件的输出路径。它不能用于制作源文件中指定部分的副本。这里我们不需要创建输出文件。它是在代码执行期间自动创建的。
  • copy(Path source, OutputStream out):将路径源中指定的文件中的所有字节复制到输出文件的输出流中。
  • copy(Path source, Path target):使用源文件和目标文件的路径复制文件。也无需在此处创建输出文件。

例子:

Java

import java.nio.file.Files;
import java.io.*;
// save the file named as GFG.java
public class GFG{
   
    // main method
    public static void main(String[] args) throws IOException{
       
        // creating two channels
        // one input and other output   
        File src = new File("C:\\Users\\Dipak\\Desktop\\input.txt");
        File dest = new File("C:\\Users\\Dipak\\Desktop\\output.txt");
             
        // using copy(InputStream,Path Target); method
        Files.copy(src.toPath(), dest.toPath());
       
        // here we are not required to have an
        // output file at the specified target.
        // same way we can use other method also.
             
    }
}

输出:

对于上面的程序,我们需要一个 input.txt 和一个 output.txt 文件。最初,两个文本文件看起来像这样

程序执行成功后,