1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.creadur.tentacles;
18
19 import org.apache.commons.io.IOUtils;
20 import org.apache.logging.log4j.*;
21 import java.io.*;
22 import java.net.URL;
23 import java.nio.file.Files;
24 import java.util.zip.ZipInputStream;
25
26 public class IOSystem {
27 private static final Logger LOG = LogManager.getLogger(IOSystem.class);
28
29 public String slurp(final File file) throws IOException {
30 final ByteArrayOutputStream out = new ByteArrayOutputStream();
31 copy(file, out);
32 return out.toString();
33 }
34
35 public String slurp(final URL url) throws IOException {
36 final ByteArrayOutputStream out = new ByteArrayOutputStream();
37 copy(url.openStream(), out);
38 return out.toString();
39 }
40
41 public void writeString(final File file, final String string) throws IOException {
42 final FileWriter out = new FileWriter(file);
43 try {
44 final BufferedWriter bufferedWriter = new BufferedWriter(out);
45 try {
46 bufferedWriter.write(string);
47 bufferedWriter.newLine();
48 } finally {
49 close(bufferedWriter);
50 }
51 } finally {
52 close(out);
53 }
54 }
55
56 private void copy(final File from, final OutputStream to) throws IOException {
57 final InputStream read = read(from);
58 try {
59 copy(read, to);
60 } finally {
61 close(read);
62 }
63 }
64
65 public void copy(final InputStream from, final File to) throws IOException {
66 final OutputStream write = write(to);
67 try {
68 copy(from, write);
69 } finally {
70 close(write);
71 }
72 }
73
74 private void copy(final InputStream from, final OutputStream to) throws IOException {
75 IOUtils.copy(from, to);
76 }
77
78 public void copy(final byte[] from, final File to) throws IOException {
79 copy(new ByteArrayInputStream(from), to);
80 }
81
82 public ZipInputStream unzip(final File file) throws IOException {
83 final InputStream read = read(file);
84 return new ZipInputStream(read);
85 }
86
87 public void close(final Closeable closeable) {
88 if (closeable == null) {
89 return;
90 }
91 try {
92 if (closeable instanceof Flushable) {
93 ((Flushable) closeable).flush();
94 }
95 } catch (final IOException e) {
96 LOG.trace("Error when trying to flush before closing {}", closeable, e);
97 }
98 try {
99 closeable.close();
100 } catch (final IOException e) {
101 LOG.trace("Error when trying to close {}", closeable, e);
102 }
103 }
104
105 private OutputStream write(final File destination) throws IOException {
106 final OutputStream out = Files.newOutputStream(destination.toPath());
107 return new BufferedOutputStream(out, 32768);
108 }
109
110 public InputStream read(final File source) throws IOException {
111 final InputStream in = Files.newInputStream(source.toPath());
112 return new BufferedInputStream(in, 32768);
113 }
114
115 public byte[] read(final InputStream in) throws IOException {
116 final ByteArrayOutputStream out = new ByteArrayOutputStream();
117 copy(in, out);
118 out.close();
119 return out.toByteArray();
120 }
121 }