BAEL-1308

This commit is contained in:
Ahmad Alsanie 2017-11-18 19:45:37 +02:00
parent b7b5543cf9
commit f7e92e326f
2 changed files with 81 additions and 0 deletions

View File

@ -0,0 +1,40 @@
package com.baeldung.copyfiles;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import org.apache.commons.io.FileUtils;
public class FileCopier {
public static File copyWithIO(File original, File copied) throws IOException {
try (InputStream in = new BufferedInputStream(new FileInputStream(original));
OutputStream out = new BufferedOutputStream(new FileOutputStream(copied))) {
byte[] buffer = new byte[1024];
int lengthRead;
while ((lengthRead = in.read(buffer)) > 0) {
out.write(buffer, 0, lengthRead);
out.flush();
}
}
return copied;
}
public static Path copyWithNio(Path original, Path copied) throws IOException {
Files.copy(original, copied, StandardCopyOption.REPLACE_EXISTING);
return copied;
}
public static File copyWithCommonsIO(File original, File copied) throws IOException {
FileUtils.copyFile(original, copied);
return copied;
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.copyfiles;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Test;
public class FileCopierTest {
@Test
public void givenIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
File copied = new File("src/test/resources/copiedWithIo.txt");
File original = new File("src/test/resources/original.txt");
copied = FileCopier.copyWithIO(original, copied);
assertTrue(copied.exists());
assertTrue(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
}
@Test
public void givenCommonsIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
File copied = new File("src/test/resources/copiedWithApacheCommons.txt");
File original = new File("src/test/resources/original.txt");
copied = FileCopier.copyWithCommonsIO(original, copied);
assertTrue(copied.exists());
assertTrue(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
}
@Test
public void givenNIO2_whenCopied_thenCopyExistsWithSameContents() throws IOException {
Path copied = Paths.get("src/test/resources/copiedWithNio.txt");
Path original = Paths.get("src/test/resources/original.txt");
copied = FileCopier.copyWithNio(original, copied);
assertTrue(Files.exists(copied));
assertTrue(Files.readAllLines(original).equals(Files.readAllLines(copied)));
}
}