|
| 1 | +package com.baeldung.stream; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.io.FileInputStream; |
| 5 | +import java.io.FileOutputStream; |
| 6 | +import java.io.IOException; |
| 7 | +import java.io.InputStream; |
| 8 | +import java.io.OutputStream; |
| 9 | +import java.nio.channels.FileChannel; |
| 10 | +import java.nio.file.Files; |
| 11 | + |
| 12 | +import org.apache.commons.io.FileUtils; |
| 13 | + |
| 14 | +public class FileCopy { |
| 15 | + |
| 16 | + public static void copyFileUsingStream(File source, File dest) throws IOException { |
| 17 | + InputStream is = null; |
| 18 | + OutputStream os = null; |
| 19 | + is = new FileInputStream(source); |
| 20 | + os = new FileOutputStream(dest); |
| 21 | + byte[] buffer = new byte[1024]; |
| 22 | + int length; |
| 23 | + while ((length = is.read(buffer)) > 0) { |
| 24 | + os.write(buffer, 0, length); |
| 25 | + } |
| 26 | + is.close(); |
| 27 | + os.close(); |
| 28 | + } |
| 29 | + |
| 30 | + public static void copyFileUsingChannel(File source, File dest) throws IOException { |
| 31 | + FileChannel sourceChannel = null; |
| 32 | + FileChannel destChannel = null; |
| 33 | + sourceChannel = new FileInputStream(source).getChannel(); |
| 34 | + destChannel = new FileOutputStream(dest).getChannel(); |
| 35 | + destChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); |
| 36 | + sourceChannel.close(); |
| 37 | + destChannel.close(); |
| 38 | + } |
| 39 | + |
| 40 | + public static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException { |
| 41 | + FileUtils.copyFile(source, dest); |
| 42 | + } |
| 43 | + |
| 44 | + public static void copyFileUsingJavaFiles(File source, File dest) throws IOException { |
| 45 | + Files.copy(source.toPath(), dest.toPath()); |
| 46 | + } |
| 47 | + |
| 48 | +} |
0 commit comments