Skip to content

Instantly share code, notes, and snippets.

@tkaczenko
Last active July 16, 2016 15:45
Show Gist options
  • Save tkaczenko/3f2e98e96342e6034d8c9dc607d46d8c to your computer and use it in GitHub Desktop.
Save tkaczenko/3f2e98e96342e6034d8c9dc607d46d8c to your computer and use it in GitHub Desktop.
Console utility for copying files written in Java
import java.io.*;
/**
* Console utility for copying file from source path to destination path
*/
public class CopyFile {
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Illegal command line agruments!\n" +
"Usage: \n\t java CopyFile <source file path> <destination file path");
return;
}
if (args[0].equals(args[1])) {
throw new IllegalArgumentException("Error: source and destination file path could not be equaled.s");
}
try {
copy(args[0], args[1]);
} catch (IOException e) {
System.out.println("Error: Something was wrong.");
e.printStackTrace();
}
}
private static void copy(String source, String destination) throws IOException {
try (InputStream inputStream = new BufferedInputStream(new FileInputStream(source))) {
try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(destination))) {
try {
int data;
do {
data = inputStream.read();
if (data != -1) {
outputStream.write(data);
}
} while (data != -1);
} catch (IOException e) {
System.out.println("Error: Copying failed.");
}
} catch (FileNotFoundException e) {
System.out.println("Error: Destination file not found.");
}
} catch (FileNotFoundException e) {
System.out.println("Error: Source file not found.");
}
}
}
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.junit.Assert.assertEquals;
/**
* Created by tkacz- on 07.07.16.
*/
public class CopyFileTest {
private String source;
private String destination;
@Before
public void setUp() throws Exception {
source = "src/test/resources/animation.gif";
destination = "src/test/resources/animation-copied.gif";
}
@After
public void tearDown() throws Exception {
Files.delete(Paths.get(destination));
}
@Test
public void whenFileExistFileShouldBeCopied() throws Exception {
String[] args = {source, destination};
CopyFile.main(args);
try (InputStream inputStream = new BufferedInputStream(new FileInputStream(source));
InputStream inputStream1 = new BufferedInputStream(new FileInputStream(destination))) {
int expected, result;
do {
expected = inputStream.read();
result = inputStream1.read();
if (expected != -1 && result != -1) {
assertEquals(expected, result);
}
} while (expected != -1 || result != -1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment