logo

Apache Commons IO to copy file content from InputStream to OutputStream

Java Code Examples for org.apache.commons.io.IOUtils.copy()

Example code below to show how to use IOUtils class of Apache Commons IO library to copy file content from an InputStream to an OutputStream.

package simplesolution.dev;

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class IOUtilsCopyExample {

    public static void main(String... args) {
        try {
            String sourceFileName = "D:\\Data\\sample.txt";
            String destinationFileName = "D:\\Data\\sample-copied.txt";

            File sourceFile = new File(sourceFileName);
            Path sourcePath = sourceFile.toPath();
            InputStream sourceStream = Files.newInputStream(sourcePath);
            try (OutputStream outputStream = new FileOutputStream(destinationFileName)) {
                IOUtils.copy(sourceStream, outputStream);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Happy Coding 😊