Java NIO Files Better Api to Copy Files


java.nio.file.Files is provided since Java 1.7 to do better files operation. This class has static methods that operate on files, directories, or other types of files. It provides 3 static overloaded methods to copy files using different parameters. All three does same things depending upon parameters.

Here are example to show how you can use them.

Below method shows how to copy file input as Path object to OutputStream using Files.copy(Path source, OutputStream out)

    public void copyExample1() {
        OutputStream out = null;
        Path source = new File("D:/tmp/2.jpg").toPath();
        try {
            out = new FileOutputStream(new File("D:/test/file.jpg"));
            Files.copy(source, out);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
            }
        }

    }

Copy InputStream to a Path file object using Files.copy(InputStream in, Path target, CopyOption… options)

    public void copyExample2() {
        InputStream in = null;
        Path target = new File("D:/test/21.jpg").toPath();
        try {
            in = new FileInputStream(new File("D:/test/file.jpg"));
            Files.copy(in,target,StandardCopyOption.REPLACE_EXISTING);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
            }
        }

    }

Copy files using Path object using Files.copy(InputStream in, Path target, CopyOption… options)

    public void copyExample3() {
        Path source = new File("D:/test/file.jpg").toPath();
        Path target = new File("D:/test/21.jpg").toPath();
        try {
            Files.copy(source,target,StandardCopyOption.REPLACE_EXISTING);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            
        }

    }