1 // CopyFileCompiled.java
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.io.OutputStream;
6 import java.nio.file.Files;
7 import java.nio.file.Paths;
8
9 /** 10 * CopyFileCompiled zeigt die Bedeutung von try-with-resources. 11 * Vergleich mit Beispiel CopyFile.java aus Teil 6. 12 * @author H.Drachenfels 13 * @version 10.1.2019 14 */
15 public final class CopyFileCompiled {
16 private CopyFileCompiled() { }
17
18 /** 19 * Kopiert eine Datei. 20 * @param args Quell- und Zieldateinamen 21 * @throws IOException bei Dateizugriffsfehlern 22 */
23 public static void main(String[] args) throws IOException {
24 /*try*/ {
25 InputStream in = Files.newInputStream(Paths.get(args[0]));
26 Throwable x = null;
27
28 try {
29 OutputStream out = Files.newOutputStream(Paths.get(args[1]));
30
31 try {
32 int b;
33 while ((b = in.read()) != -1) {
34 out.write(b);
35 }
36 } catch (Throwable t) {
37 x = t;
38 throw t;
39 } finally {
40 if (x != null) {
41 try {
42 out.close();
43 } catch (Throwable t) {
44 x.addSuppressed(t);
45 }
46 } else {
47 out.close();
48 }
49 }
50 } catch (Throwable t) {
51 x = t;
52 throw t;
53 } finally {
54 if (x != null) {
55 try {
56 in.close();
57 } catch (Throwable t) {
58 x.addSuppressed(t);
59 }
60 } else {
61 in.close();
62 }
63 }
64 }
65 }
66 }
67