KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > scriptella > util > IOUtils


1 /*
2  * Copyright 2006-2007 The Scriptella Project Team.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package scriptella.util;
17
18 import java.io.BufferedReader JavaDoc;
19 import java.io.BufferedWriter JavaDoc;
20 import java.io.ByteArrayOutputStream JavaDoc;
21 import java.io.Closeable JavaDoc;
22 import java.io.File JavaDoc;
23 import java.io.FileOutputStream JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.io.InputStreamReader JavaDoc;
27 import java.io.OutputStream JavaDoc;
28 import java.io.OutputStreamWriter JavaDoc;
29 import java.io.Reader JavaDoc;
30 import java.io.UnsupportedEncodingException JavaDoc;
31 import java.io.Writer JavaDoc;
32 import java.net.MalformedURLException JavaDoc;
33 import java.net.URL JavaDoc;
34
35 /**
36  * I/O utility methods.
37  *
38  * @author Fyodor Kupolov
39  * @version 1.0
40  */

41 public final class IOUtils {
42     //Singleton
43
private IOUtils() {
44     }
45
46     /**
47      * Default value of maximum stream size for arrays conversion
48      */

49     static final long MAX_LENGTH = 1024 * 10000; //10Mb
50

51     /**
52      * Silently closes data.
53      *
54      * @param closeable data to close
55      */

56     public static void closeSilently(Closeable JavaDoc closeable) {
57         if (closeable != null) {
58             try {
59                 closeable.close();
60             } catch (Exception JavaDoc e) {
61                 ExceptionUtils.ignoreThrowable(e);
62             }
63         }
64     }
65
66     /**
67      * Silently closes a collection of objects.
68      * @param closeables iterable closeables. Null value allowed.
69      * @see #closeSilently(java.io.Closeable)
70      */

71     public static void closeSilently(Iterable JavaDoc<? extends Closeable JavaDoc> closeables) {
72         if (closeables != null) {
73             for (Closeable JavaDoc closeable : closeables) {
74                 closeSilently(closeable);
75             }
76         }
77     }
78
79
80     /**
81      * Loads a reader content into a string.
82      *
83      * @param reader reader to load content from. Closed at the end of the operation.
84      * @return string representation of reader content.
85      */

86     public static String JavaDoc toString(Reader JavaDoc reader) throws IOException JavaDoc {
87         return toString(reader, MAX_LENGTH);
88
89     }
90
91     /**
92      * Loads a reader content into a string.
93      *
94      * @param reader reader to load content from. Closed at the end of the operation.
95      * @param maxLength max number of characters to read before throwing a Content Too Long Exception.
96      * @return string representation of reader content.
97      */

98     public static String JavaDoc toString(final Reader JavaDoc reader, final long maxLength) throws IOException JavaDoc {
99         char cb[] = new char[4096];
100         StringBuilder JavaDoc sb = new StringBuilder JavaDoc(cb.length);
101         long len = 0;
102
103         try {
104             for (int n; (n = reader.read(cb)) >= 0;) {
105                 len += n;
106                 if (len > maxLength) {
107                     throw new IOException JavaDoc("Content too long to fit in memory");
108                 }
109                 sb.append(cb, 0, n);
110             }
111         } finally {
112             closeSilently(reader);
113         }
114
115         return sb.toString();
116     }
117
118     /**
119      * Loads an input stream content into a byte array.
120      *
121      * @param is stream to load. Closed at the end of the operation.
122      * @return stream bytes
123      * @throws IOException if I/O error occurs or stream length exceeds the {@link #MAX_LENGTH}.
124      */

125     public static byte[] toByteArray(InputStream JavaDoc is) throws IOException JavaDoc {
126         return toByteArray(is, MAX_LENGTH);
127     }
128
129     /**
130      * Loads an input stream content into a byte array.
131      *
132      * @param is stream to load. Closed at the end of the operation.
133      * @param maxLength maxLength max number of bytes to read before throwing a Content Too Long Exception.
134      * @return stream bytes
135      * @throws IOException
136      */

137     public static byte[] toByteArray(InputStream JavaDoc is, long maxLength) throws IOException JavaDoc {
138         byte b[] = new byte[4096];
139         ByteArrayOutputStream JavaDoc os = new ByteArrayOutputStream JavaDoc(b.length);
140         long len = 0;
141
142         try {
143             for (int n; (n = is.read(b)) >= 0;) {
144                 len += n;
145                 if (len > maxLength) {
146                     throw new IOException JavaDoc("Content too long to fit in memory");
147                 }
148                 os.write(b, 0, n);
149             }
150         } finally {
151             closeSilently(is);
152         }
153
154         return os.toByteArray();
155     }
156
157     /**
158      * Opens output stream for specified URL.
159      * <p>This method is a helper for url.openConnection().getOutputStream().
160      * Additionally a file: URLs are supported,
161      * see <a HREF="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4191800">
162      * FileURLConnection doesn't implement getOutputStream()</a>
163      *
164      * @param url URL to open an output stream.
165      * @return output stream for URL.
166      * @throws IOException if an I/O error occurs while creating the output stream.
167      */

168     public static OutputStream JavaDoc getOutputStream(final URL JavaDoc url) throws IOException JavaDoc {
169         if ("file".equals(url.getProtocol())) {
170             return new FileOutputStream JavaDoc(url.getFile());
171         } else {
172             return url.openConnection().getOutputStream();
173         }
174
175     }
176
177     /**
178      * @return buffered reader for specified input stream.
179      * @see #getReader(java.io.InputStream, String, boolean)
180      *
181      */

182     public static Reader JavaDoc getReader(final InputStream JavaDoc is, final String JavaDoc enc) throws UnsupportedEncodingException JavaDoc {
183         return getReader(is, enc, true);
184     }
185
186     /**
187      * Returns reader for specified input stream and charset name.
188      * @param is source input stream.
189      * @param enc charset name, null means default.
190      * @param buffered true if buffered reader should be used.
191      * @return reader for inputstream.
192      * @throws UnsupportedEncodingException If the named charset is not supported
193      */

194     public static Reader JavaDoc getReader(final InputStream JavaDoc is, final String JavaDoc enc, final boolean buffered) throws UnsupportedEncodingException JavaDoc {
195         Reader JavaDoc r = enc == null ? new InputStreamReader JavaDoc(is) : new InputStreamReader JavaDoc(is, enc);
196         return buffered ? new BufferedReader JavaDoc(r) : r;
197     }
198
199     /**
200      * Optionally makes a buffered reader from the specified one.
201      * <p>If specified reader is buffered the object is returned unchanged.
202      * @param reader reader to convert.
203      * @return buffered reader.
204      */

205     public static BufferedReader JavaDoc asBuffered(Reader JavaDoc reader) {
206         if (reader==null) {
207             throw new IllegalArgumentException JavaDoc("Reader cannot be null");
208         }
209         return (reader instanceof BufferedReader JavaDoc?(BufferedReader JavaDoc)reader:new BufferedReader JavaDoc(reader));
210     }
211
212     /**
213      * Optionally makes a buffered writer from the specified one.
214      * <p>If specified writer is buffered the object is returned unchanged.
215      * @param writer writer to convert.
216      * @return buffered writer.
217      */

218     public static BufferedWriter JavaDoc asBuffered(Writer JavaDoc writer) {
219         if (writer==null) {
220             throw new IllegalArgumentException JavaDoc("Writer cannot be null");
221         }
222         return (writer instanceof BufferedWriter JavaDoc?(BufferedWriter JavaDoc)writer:new BufferedWriter JavaDoc(writer));
223     }
224
225
226     /**
227      * @return buffered writer for specified output stream.
228      * @see #getWriter(java.io.OutputStream, String, boolean)
229      *
230      */

231     public static Writer JavaDoc getWriter(final OutputStream JavaDoc os, final String JavaDoc enc) throws IOException JavaDoc {
232         return getWriter(os, enc, true);
233     }
234
235     /**
236      * Returns writer for specified output stream and charset name.
237      * @param os source output stream.
238      * @param enc charset name, null means default.
239      * @param buffered true if buffered reader should be used.
240      * @return reader for inputstream.
241      * @throws UnsupportedEncodingException If the named charset is not supported
242      */

243     public static Writer JavaDoc getWriter(final OutputStream JavaDoc os, final String JavaDoc enc, final boolean buffered) throws IOException JavaDoc {
244         Writer JavaDoc w = enc == null ? new OutputStreamWriter JavaDoc(os) : new OutputStreamWriter JavaDoc(os, enc);
245         return buffered ? new BufferedWriter JavaDoc(w) : w;
246     }
247
248     /**
249      * A replacement for a deprecated File.toURL() method.
250      * @param file file to convert to URL.
251      * @return URL representing the file location.
252      * @throws MalformedURLException If a protocol handler for the URL could not be found,
253      * or if some other error occurred while constructing the URL.
254      */

255     public static URL JavaDoc toUrl(File JavaDoc file) throws MalformedURLException JavaDoc {
256         return file.toURI().toURL();
257     }
258
259 }
260
Popular Tags