Skip to content

Instantly share code, notes, and snippets.

@rhmoller
Created July 22, 2011 09:35
Show Gist options
  • Save rhmoller/1099165 to your computer and use it in GitHub Desktop.
Save rhmoller/1099165 to your computer and use it in GitHub Desktop.
Java 7: Try with Resources (ARM)
public void newStyleCopyFile(File source, File target) {
try (
FileInputStream in = new FileInputStream(source);
FileOutputStream out = new FileOutputStream(target);
) {
byte[] buffer = new byte[4096];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void oldStyleCopyFile(File source, File target) {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(source);
out = new FileOutputStream(target);
byte[] buffer = new byte[4096];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void shortCopyFile(File source, File target) {
try {
Files.copy(source.toPath(), target.toPath());
} catch (IOException e) {
e.printStackTrace();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment