1
2
3
4
5 package net.sf.jlayercheck.util.io;
6
7 import java.io.File;
8 import java.io.FileInputStream;
9 import java.io.FileOutputStream;
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.io.InputStreamReader;
13 import java.io.OutputStream;
14 import java.io.Reader;
15 import java.io.StringWriter;
16 import java.io.Writer;
17 import java.net.URL;
18
19
20
21
22
23
24
25
26 public class IOHelper {
27
28
29 public static final int BUFFER_SIZE = 2048;
30
31
32
33
34
35
36 public static void close(OutputStream stream) {
37 if (stream != null) {
38 try {
39 stream.close();
40 } catch (IOException e) {
41
42 }
43 }
44 }
45
46
47
48
49
50
51 public static void close(InputStream stream) {
52 if (stream != null) {
53 try {
54 stream.close();
55 } catch (IOException e) {
56
57 }
58 }
59 }
60
61
62
63
64
65
66 public static void close(Reader reader) {
67 if (reader != null) {
68 try {
69 reader.close();
70 } catch (IOException e) {
71
72 }
73 }
74 }
75
76
77
78
79
80
81 public static void close(Writer writer) {
82 if (writer != null) {
83 try {
84 writer.close();
85 } catch (IOException e) {
86
87 }
88 }
89 }
90
91
92
93
94
95
96
97
98
99
100
101
102 public static void copy(InputStream in, OutputStream out)
103 throws IOException {
104 byte[] buffer = new byte[BUFFER_SIZE];
105 int len = in.read(buffer);
106 while (len > 0) {
107 out.write(buffer, 0, len);
108 len = in.read(buffer);
109 }
110 }
111
112
113
114
115
116
117
118
119
120
121 public static void copy(Reader in, Writer out) throws IOException {
122 char[] buffer = new char[BUFFER_SIZE];
123 int len = in.read(buffer);
124 while (len > 0) {
125 out.write(buffer, 0, len);
126 len = in.read(buffer);
127 }
128 }
129
130
131
132
133
134
135
136
137
138 public static void copy(File from, File to) {
139 FileInputStream in = null;
140 FileOutputStream out = null;
141 try {
142 in = new FileInputStream(from);
143 out = new FileOutputStream(to);
144 } catch (IOException e) {
145 throw new RuntimeException("Error copying " + from + " to " + to, e);
146 } finally {
147 close(in);
148 close(out);
149 }
150 }
151
152
153
154
155
156
157
158
159
160 public static void copy(URL from, File to) {
161 InputStream in = null;
162 FileOutputStream out = null;
163 try {
164 in = from.openStream();
165 out = new FileOutputStream(to);
166 } catch (IOException e) {
167 throw new RuntimeException("Error copying " + from + " to " + to, e);
168 } finally {
169 close(in);
170 close(out);
171 }
172 }
173
174
175
176
177
178
179
180
181
182
183 public static String readContent(URL url) {
184 StringWriter writer = new StringWriter();
185 Reader reader = null;
186 try {
187 reader = new InputStreamReader(url.openStream());
188 copy(reader, writer);
189 } catch (IOException e) {
190 throw new RuntimeException("Cannot read " + url, e);
191 } finally {
192 close(reader);
193 }
194 return writer.toString();
195 }
196
197 }