root/trunk/src/java/org/jcoderz/commons/util/IoUtil.java

Revision 1011, 10.3 kB (checked in by amandel, 7 months ago)

Aligned svn keyword settings.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
Line 
1/*
2 * $Id$
3 *
4 * Copyright 2006, The jCoderZ.org Project. All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are
8 * met:
9 *
10 *    * Redistributions of source code must retain the above copyright
11 *      notice, this list of conditions and the following disclaimer.
12 *    * Redistributions in binary form must reproduce the above
13 *      copyright notice, this list of conditions and the following
14 *      disclaimer in the documentation and/or other materials
15 *      provided with the distribution.
16 *    * Neither the name of the jCoderZ.org Project nor the names of
17 *      its contributors may be used to endorse or promote products
18 *      derived from this software without specific prior written
19 *      permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
28 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
29 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
30 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
31 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33package org.jcoderz.commons.util;
34
35import java.io.ByteArrayOutputStream;
36import java.io.File;
37import java.io.FileInputStream;
38import java.io.FileOutputStream;
39import java.io.IOException;
40import java.io.InputStream;
41import java.io.OutputStream;
42import java.io.RandomAccessFile;
43import java.io.Reader;
44import java.io.StringWriter;
45import java.io.Writer;
46import java.net.Socket;
47import java.nio.channels.Channel;
48import java.util.logging.Level;
49import java.util.logging.Logger;
50
51/**
52 * Collects some I/O utility functions.
53 *
54 * @author Michael Griffel
55 * @author Andreas Mandel
56 */
57public final class IoUtil
58{
59   /** class name for use in logger */
60   private static final String CLASSNAME = IoUtil.class.getName();
61
62   /** logging facility */
63   private static final Logger logger = Logger.getLogger(CLASSNAME);
64
65   private static final int BUFFER_SIZE = 4096;
66
67   /**
68    * Constructor.
69    */
70   private IoUtil ()
71   {
72      // Utility class -- only static methods
73   }
74
75   /**
76    * Closes the input stream (safe).
77    *
78    * This method tries to close the given input stream and
79    * if an IOException occurs a message with the level
80    * {@link Level#FINE} is logged. It's safe to pass a
81    * <code>null</code> reference for the argument.
82    *
83    * @param in the input stream that should be closed.
84    */
85   public static void close (InputStream in)
86   {
87      if (in != null)
88      {
89         try
90         {
91            in.close();
92         }
93         catch (IOException x)
94         {
95            logCloseFailedWarningMessage(
96                  InputStream.class, in.getClass(), x);
97         }
98      }
99   }
100
101   /**
102    * Closes the output stream (safe).
103    *
104    * This method tries to close the given output stream and
105    * if an IOException occurs a message with the level
106    * {@link Level#FINE} is logged. It's safe to pass a
107    * <code>null</code> reference for the argument.
108    *
109    * @param out the output stream that should be closed.
110    */
111   public static void close (OutputStream out)
112   {
113      if (out != null)
114      {
115         try
116         {
117            out.close();
118         }
119         catch (IOException x)
120         {
121            logCloseFailedWarningMessage(
122                  OutputStream.class, out.getClass(), x);
123         }
124      }
125   }
126
127   /**
128    * Closes the reader (safe).
129    *
130    * This method tries to close the given reader and if an IOException occurs
131    * a message with the level {@link Level#FINE} is logged. It's safe
132    * to pass a <code>null</code> reference for the argument.
133    *
134    * @param reader the reader that should be closed.
135    */
136   public static void close (Reader reader)
137   {
138      if (reader != null)
139      {
140         try
141         {
142            reader.close();
143         }
144         catch (IOException x)
145         {
146            logCloseFailedWarningMessage(
147                  Reader.class, reader.getClass(), x);
148         }
149      }
150   }
151
152   /**
153    * Closes the RandomAccessFile (safe).
154    *
155    * This method tries to close the given RandomAccessFile and if an
156    * IOException occurs a message with the level {@link Level#FINE}
157    * is logged. It's safe to pass a <code>null</code> reference
158    * for the argument.
159    *
160    * @param randomAccessFile the randomAccessFile that should be closed.
161    */
162   public static void close (RandomAccessFile randomAccessFile)
163   {
164      if (randomAccessFile != null)
165      {
166         try
167         {
168            randomAccessFile.close();
169         }
170         catch (IOException x)
171         {
172            logCloseFailedWarningMessage(
173                  Reader.class, randomAccessFile.getClass(), x);
174         }
175      }
176   }
177
178   /**
179    * Closes the writer (safe).
180    *
181    * This method tries to close the given writer and if an IOException occurs
182    * a message with the level {@link Level#FINE} is logged. It's safe
183    * to pass a <code>null</code> reference for the argument.
184    *
185    * @param writer the writer that should be closed.
186    */
187   public static void close (Writer writer)
188   {
189      if (writer != null)
190      {
191         try
192         {
193            writer.close();
194         }
195         catch (IOException x)
196         {
197            logCloseFailedWarningMessage(
198                  Writer.class, writer.getClass(), x);
199         }
200      }
201   }
202
203   /**
204    * Closes the channel (safe).
205    *
206    * This method tries to close the given channel and if an IOException occurs
207    * a message with the level {@link Level#FINE} is logged. It's safe
208    * to pass a <code>null</code> reference for the argument.
209    *
210    * @param channel the channel that should be closed.
211    */
212   public static void close (Channel channel)
213   {
214      if (channel != null)
215      {
216         try
217         {
218            channel.close();
219         }
220         catch (IOException x)
221         {
222            logCloseFailedWarningMessage(Channel.class, channel.getClass(), x);
223         }
224      }
225   }
226
227   /**
228    * Closes the socket (safe).
229    *
230    * This method tries to close the given socket and if an IOException occurs
231    * a message with the level {@link Level#FINE} is logged. It's safe
232    * to pass a <code>null</code> reference for the argument.
233    *
234    * @param socket the socket that should be closed.
235    */
236   public static void close (Socket socket)
237   {
238      if (socket != null)
239      {
240         try
241         {
242             socket.close();
243         }
244         catch (IOException x)
245         {
246            logCloseFailedWarningMessage(Channel.class, socket.getClass(), x);
247         }
248      }
249   }
250
251   /**
252    * Reads <code>expectedLength</code> bytes from the input
253    * stream <code>in</code>.
254    *
255    * @param in the input stream to read from.
256    * @param expectedLength the expected size.
257    * @return an byte array with <code>expectedLength</code> bytes.
258    * @throws IOException in an I/O error occurs or if the read size is not the
259    *       expected size.
260    */
261   public static byte[] readFully (InputStream in, int expectedLength)
262         throws IOException
263   {
264      final byte[] buffer = new byte[expectedLength];
265      int pos = 0;
266      int read = 0;
267
268      while ((read = in.read(buffer, pos, expectedLength - pos)) >= 0)
269      {
270         pos += read;
271         if (expectedLength == pos)
272         {
273            break;
274         }
275      }
276
277      if (expectedLength != pos)
278      {
279         throw new IOException(
280               "Buffer underread. Could not read " + expectedLength
281               + " bytes from stream. Expected was " + expectedLength
282               + " bytes, but got only " + pos + " bytes");
283      }
284
285      return buffer;
286   }
287
288   /**
289    * Reads all bytes from the input stream <code>in</code>.
290    *
291    * @param in the input stream to read from.
292    * @return an byte array with read bytes.
293    * @throws IOException in an I/O error occurs.
294    */
295   public static byte[] readFully (InputStream in)
296         throws IOException
297   {
298      final byte[] buffer = new byte[BUFFER_SIZE];
299      int read = 0;
300      final ByteArrayOutputStream out = new ByteArrayOutputStream();
301
302      while ((read = in.read(buffer)) >= 0)
303      {
304         out.write(buffer, 0, read);
305      }
306
307      return out.toByteArray();
308   }
309
310   /**
311    * Reads all characters from the reader <code>in</code>.
312    *
313    * @param in the Reader to read from.
314    * @return an String containing the read data
315    * @throws IOException in an I/O error occurs.
316    */
317   public static String readFully (Reader in)
318         throws IOException
319   {
320      final char[] buffer = new char[BUFFER_SIZE];
321      int read = 0;
322      final StringWriter out = new StringWriter();
323
324      while ((read = in.read(buffer)) >= 0)
325      {
326         out.write(buffer, 0, read);
327      }
328
329      return out.toString();
330   }
331
332   /**
333    * Reads all data from in and copies it to the out stream.
334    * @param in the stream to read.
335    * @param out the stream to write.
336    * @throws IOException if an I/O issue occurs.
337    */
338   public static void copy (InputStream in, OutputStream out)
339         throws IOException
340   {
341      final byte[] buffer = new byte[BUFFER_SIZE];
342      int read;
343
344      while ((read = in.read(buffer)) >= 0)
345      {
346         out.write(buffer, 0, read);
347      }
348   }
349
350   /**
351    * Copies file <tt>src</tt> to file <tt>dest</tt>.
352    * @param src the source file.
353    * @param dest the destination file.
354    * @throws IOException if an I/O issue occurs.
355    */
356   public static void copy (File src, File dest)
357         throws IOException
358   {
359      final InputStream in = new FileInputStream(src);
360      final OutputStream out = new FileOutputStream(dest);
361      try
362      {
363         copy(in, out);
364      }
365      finally
366      {
367         close(in);
368         close(out);
369      }
370   }
371
372
373   private static void logCloseFailedWarningMessage (
374         Class resource, Class clazz, IOException x)
375   {
376      logger.log(Level.FINE, "Error while closing " + resource.getName() + ": "
377            + clazz.getName() + ".close()", x);
378   }
379
380}
Note: See TracBrowser for help on using the browser.