copyInputStreamToFile()
is a FileUtils
class 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 do not already exist. The destination file will be overwritten if it already exists. The source stream is closed.
Refer to What is FileUtils.copyToFile() in Java? for the method that keeps the stream open after the copy is completed.
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;
public static void copyInputStreamToFile(final InputStream source, final File destination)
final InputStream source
: This is the input stream to copy.final File destination
: This is the destination file.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/temp/1.txt";InputStream inputStream = new FileInputStream(srcFilePath);System.out.println("Contents of the " + srcFilePath + " is as follows:");printFile(srcFilePath);String dstFilePath = "/Users/educative/Documents/temp/3.txt";File dstFile = new File(dstFilePath);System.out.println("Copying the input file stream to target file...");FileUtils.copyInputStreamToFile(inputStream, dstFile);System.out.println("Contents of the " +dstFilePath + " is as follows:");printFile(dstFilePath);}}
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 using the method FileUtils.copyInputStreamToFile()
.
As the method closes the input stream, we do not need to explicitly close the stream using the close()
method on the stream object. Finally, we print the contents of the target file.
The output of the code will be as follows:
Contents of the /Users/educative/Documents/temp/1.txt is as follows:
hello-educative
hi-edpresso
Copying the input file stream to target file...
Contents of the /Users/educative/Documents/temp/3.txt is as follows:
hello-educative
hi-edpresso
Free Resources