What is FileUtils.copyToFile() in Java?

copyToFile() is a staticthe methods in Java that can be called without creating an object of the class. method of FileUtils that is used to copy bytes from an input stream source to a file. The directories up to the destination file will be created if they don’t already exist. The destination file will be overwritten if it already exists. The source stream is left open after the copy operation is completed.

Refer here to learn more about FileUtils.copyInputStreamToFile.

How to import FileUtils

The definition of FileUtils can be found in the Apache Commons IO package, which we can add to the Maven project by adding the following dependency to the pom.xml file:


<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
</dependency>

For other versions of the commons-io package, refer to the Maven Repository.

You can import the FileUtils class as follows:


import org.apache.commons.io.FileUtils;

Syntax

public static void copyToFile(final InputStream inputStream, final File file)

Parameters

  • final InputStream inputStream: The input stream to copy.
  • final File file: The destination file.

Return value

This method does not return anything.

Code

import org.apache.commons.io.FileUtils;
import java.io.*;
public class Main{
private static void printFile(String filePath) throws IOException {
BufferedReader bufferedReader
= new BufferedReader(new FileReader(filePath));
String string;
while ((string = bufferedReader.readLine()) != null)
System.out.println(string);
}
public static void main(String[] args) throws IOException {
String srcFilePath = "/Users/educative/Documents/src/1.txt";
InputStream inputStream = new FileInputStream(srcFilePath);
System.out.println("Contents of the " + srcFilePath + " is as follows:");
printFile(srcFilePath);
String dstFilePath = "/Users/educative/Documents/dst/3.txt";
File dstFile = new File(dstFilePath);
System.out.println("Copying the input file stream to target file...");
FileUtils.copyToFile(inputStream, dstFile);
inputStream.close();
System.out.println("Contents of the " +dstFilePath + " is as follows:");
printFile(dstFilePath);
}
}

Explanation

In the code above, we create an input stream from a file. Next, we use the created input stream to copy to the destination file with the FileUtils.copyToFile() method. Since the method does not close the input stream, we use close() on the stream object to explicitly close the stream. Finally, we print the contents of the target file.

Output

The output of the code will be as follows:

Contents of the /Users/educative/Documents/src/1.txt is as follows:
hello-educative
Copying the input file stream to target file...
Contents of the /Users/educative/Documents/dst/3.txt is as follows:
hello-educative

Free Resources

Attributions:
  1. undefined by undefined