View Javadoc

1   /*
2    FileUtils.java
3    Creation date : 07/03/2009
4    Copyright © Benjamin Croizet (graffity2199@yahoo.fr)
5   
6    This program is free software; you can redistribute it and/or
7    modify it under the terms of the GNU General Public License
8    or GNU Lesser General Public License as published by the
9    Free Software Foundation; either version 3 of the License,
10   or (at your option) any later version.
11  
12   This program is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16  
17   You should have received copies of the GNU General Public License
18   and GNU Lesser General Public License along with this program;
19   if not, write to the Free Software Foundation, Inc.,
20   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21   http://www.fsf.org/licensing/licenses/gpl.html
22   http://www.gnu.org/licenses/lgpl.html
23   */
24  
25  package net.sourceforge.plantumldependency.common.utils.file;
26  
27  import static java.util.logging.Level.INFO;
28  import static java.util.logging.Level.SEVERE;
29  import static java.util.logging.Logger.getLogger;
30  import static net.sourceforge.plantumldependency.common.constants.CommonConstants.MINUS_ONE_RETURN_CODE;
31  import static net.sourceforge.plantumldependency.common.constants.log.ErrorConstants.CLOSE_FILE_ERROR;
32  import static net.sourceforge.plantumldependency.common.constants.log.ErrorConstants.CLOSE_STREAM_ERROR;
33  import static net.sourceforge.plantumldependency.common.constants.log.ErrorConstants.READ_FILE_ERROR;
34  import static net.sourceforge.plantumldependency.common.constants.log.ErrorConstants.WRITE_FILE_ERROR;
35  import static net.sourceforge.plantumldependency.common.constants.log.InfoConstants.READ_FILE_INFO;
36  import static net.sourceforge.plantumldependency.common.constants.log.InfoConstants.WRITE_FILE_INFO;
37  import static net.sourceforge.plantumldependency.common.utils.log.LogUtils.buildLogString;
38  
39  import java.io.Closeable;
40  import java.io.File;
41  import java.io.FileInputStream;
42  import java.io.FileWriter;
43  import java.io.IOException;
44  import java.io.InputStream;
45  import java.io.InputStreamReader;
46  import java.io.Reader;
47  import java.io.StringWriter;
48  import java.util.logging.Logger;
49  
50  /**
51   * The class utilities managing files.
52   *
53   * @author Benjamin Croizet (<a href="mailto:graffity2199@yahoo.fr>graffity2199@yahoo.fr</a>)
54   * @since 1.3.0
55   * @version 1.3.0
56   */
57  public abstract class FileUtils {
58  
59      /** The class logger. */
60      private static final transient Logger LOGGER = getLogger(FileUtils.class.getName());
61  
62      /**
63       * Properly close a {@link Closeable} object.
64       *
65       * @param closeable
66       *            the {@link Closeable} instance to close, mustn't be <code>null</code>.
67       * @since 1.3.0
68       */
69      public static void closeCloseable(final Closeable closeable) {
70          if (closeable != null) {
71              try {
72                  closeable.close();
73              } catch (final IOException e) {
74                  LOGGER.log(SEVERE, CLOSE_STREAM_ERROR, e);
75              }
76          }
77      }
78  
79      /**
80       * Properly close a {@link Closeable} object.
81       *
82       * @param closeable
83       *            the {@link Closeable} instance to close, mustn't be <code>null</code>.
84       * @param closeableFile
85       *            the closeable {@link File} to log if any exception occurs.
86       * @since 1.3.0
87       */
88      public static void closeCloseable(final Closeable closeable, final File closeableFile) {
89          closeCloseable(closeable, closeableFile.toString());
90      }
91  
92      /**
93       * Properly close a {@link Closeable} object.
94       *
95       * @param closeable
96       *            the {@link Closeable} instance to close, mustn't be <code>null</code>.
97       * @param closeableName
98       *            the closeable name to log if any exception occurs.
99       * @since 1.3.0
100      */
101     public static void closeCloseable(final Closeable closeable, final String closeableName) {
102         if (closeable != null) {
103             try {
104                 closeable.close();
105             } catch (final IOException e) {
106                 LOGGER.log(SEVERE, buildLogString(CLOSE_FILE_ERROR, closeableName), e);
107             }
108         }
109     }
110 
111     /**
112      * This method reads the following file path as a <code>String</code>. It uses the default
113      * encoding when reading the file.
114      *
115      * @param file
116      *            the file to read from, must'nt be <code>null</code>.
117      * @return the file content as a <code>String</code>, or the <code>null</code> constant if any
118      *         error has occurred.
119      * @since 1.3.0
120      */
121     public static String readFileIntoString(final File file) {
122         return readFileIntoString(file, null);
123     }
124 
125     /**
126      * This method reads the following file path as a <code>String</code>.
127      *
128      * @param file
129      *            the file to read from, must'nt be <code>null</code>.
130      * @param charsetName
131      *            The name of a supported {@link java.nio.charset.Charset}.
132      * @return the file content as a <code>String</code>, or the <code>null</code> constant if any
133      *         error has occurred.
134      * @since 1.3.0
135      */
136     public static String readFileIntoString(final File file, final String charsetName) {
137         assert file != null : "file is null";
138 
139         LOGGER.log(INFO, buildLogString(READ_FILE_INFO, new Object[] {file}));
140 
141         FileInputStream fi = null;
142         String result = null;
143 
144         try {
145             fi = new FileInputStream(file);
146             result = readStreamIntoString(fi, charsetName);
147         } catch (final IOException e) {
148             LOGGER.log(SEVERE, buildLogString(READ_FILE_ERROR, file), e);
149         } finally {
150             closeCloseable(fi, file);
151         }
152 
153         return result;
154     }
155 
156     /**
157      * This method reads the following file path as a <code>String</code>. It uses the default
158      * encoding when reading the file.
159      *
160      * @param pathName
161      *            the file pathname to read from, must'nt be <code>null</code>.
162      * @return the file content as a <code>String</code>, or the <code>null</code> constant if any
163      *         error has occurred.
164      * @since 1.3.0
165      */
166     public static String readFileIntoString(final String pathName) {
167         return readFileIntoString(pathName, null);
168     }
169 
170     /**
171      * This method reads the following file path as a <code>String</code>.
172      *
173      * @param pathName
174      *            the file pathname to read from, must'nt be <code>null</code>.
175      * @param charsetName
176      *            The name of a supported {@link java.nio.charset.Charset}.
177      * @return the file content as a <code>String</code>, or the <code>null</code> constant if any
178      *         error has occurred.
179      * @since 1.3.0
180      */
181     public static String readFileIntoString(final String pathName, final String charsetName) {
182         assert pathName != null : "pathName is null";
183 
184         return readFileIntoString(new File(pathName), charsetName);
185     }
186 
187     /**
188      * This method reads the following file path as a <code>String</code>. It uses the default
189      * encoding when reading the file.
190      *
191      * @param file
192      *            the file to read from, must'nt be <code>null</code>.
193      * @return the file content as a <code>StringBuffer</code>, or the <code>null</code> constant if
194      *         any error has occurred.
195      * @since 1.3.0
196      */
197     public static StringBuffer readFileIntoStringBuffer(final File file) {
198         return readFileIntoStringBuffer(file, null);
199     }
200 
201     /**
202      * This method reads the following file path as a <code>String</code>.
203      *
204      * @param file
205      *            the file to read from, must'nt be <code>null</code>.
206      * @param charsetName
207      *            The name of a supported {@link java.nio.charset.Charset}.
208      * @return the file content as a <code>StringBuffer</code>, or the <code>null</code> constant if
209      *         any error has occurred.
210      * @since 1.3.0
211      */
212     public static StringBuffer readFileIntoStringBuffer(final File file, final String charsetName) {
213         assert file != null : "file is null";
214 
215         LOGGER.log(INFO, buildLogString(READ_FILE_INFO, new Object[] {file}));
216 
217         FileInputStream fi = null;
218         StringBuffer result = null;
219 
220         try {
221             fi = new FileInputStream(file);
222             result = readStreamIntoStringBuffer(fi, charsetName);
223         } catch (final IOException e) {
224             LOGGER.log(SEVERE, buildLogString(READ_FILE_ERROR, file), e);
225         } finally {
226             closeCloseable(fi, file);
227         }
228 
229         return result;
230     }
231 
232     /**
233      * This method reads the following file path as a <code>String</code>. It uses the default
234      * encoding when reading the file.
235      *
236      * @param pathName
237      *            the file pathname to read from, must'nt be <code>null</code>.
238      * @return the file content as a <code>StringBuffer</code>, or the <code>null</code> constant if
239      *         any error has occurred.
240      * @since 1.3.0
241      */
242     public static StringBuffer readFileIntoStringBuffer(final String pathName) {
243         return readFileIntoStringBuffer(pathName, null);
244     }
245 
246     /**
247      * This method reads the following file path as a <code>String</code>.
248      *
249      * @param pathName
250      *            the file pathname to read from, must'nt be <code>null</code>.
251      * @param charsetName
252      *            The name of a supported {@link java.nio.charset.Charset}.
253      * @return the file content as a <code>StringBuffer</code>, or the <code>null</code> constant if
254      *         any error has occurred.
255      * @since 1.3.0
256      */
257     public static StringBuffer readFileIntoStringBuffer(final String pathName, final String charsetName) {
258         assert pathName != null : "pathName is null";
259 
260         return readFileIntoStringBuffer(new File(pathName), charsetName);
261     }
262 
263     /**
264      * This method reads the following stream as a <code>String</code>. Doesn't close the stream. It
265      * uses the default encoding when reading the stream.
266      *
267      * @param stream
268      *            the input stream to read from, must'nt be <code>null</code>.
269      * @return the stream content as a <code>String</code>, or the <code>null</code> constant if any
270      *         error has occurred.
271      * @throws IOException
272      *             if any exception occurs while reading the stream.
273      * @since 1.3.0
274      */
275     public static String readStreamIntoString(final InputStream stream) throws IOException {
276         return readStreamIntoString(stream, null);
277     }
278 
279     /**
280      * This method reads the following stream as a <code>String</code>. Doesn't close the stream.
281      *
282      * @param stream
283      *            the input stream to read from, must'nt be <code>null</code>.
284      * @param charsetName
285      *            The name of a supported {@link java.nio.charset.Charset}.
286      * @return the stream content as a <code>String</code>, or the <code>null</code> constant if any
287      *         error has occurred.
288      * @throws IOException
289      *             if any exception occurs while reading the stream.
290      * @since 1.3.0
291      */
292     public static String readStreamIntoString(final InputStream stream, final String charsetName) throws IOException {
293         return readStreamIntoStringBuffer(stream, charsetName).toString();
294     }
295 
296     /**
297      * This method reads the following stream as a <code>String</code>. Doesn't close the stream. It
298      * uses the default encoding when reading the stream.
299      *
300      * @param stream
301      *            the input stream to read from, must'nt be <code>null</code>.
302      * @return the stream content as a <code>StringBuffer</code>, or the <code>null</code> constant
303      *         if any error has occurred.
304      * @throws IOException
305      *             if any exception occurs while reading the stream.
306      * @since 1.3.0
307      */
308     public static StringBuffer readStreamIntoStringBuffer(final InputStream stream) throws IOException {
309         return readStreamIntoStringBuffer(stream, null);
310     }
311 
312     /**
313      * This method reads the following stream as a <code>String</code>. Doesn't close the stream.
314      *
315      * @param stream
316      *            the input stream to read from, must'nt be <code>null</code>.
317      * @param charsetName
318      *            The name of a supported {@link java.nio.charset.Charset}.
319      * @return the stream content as a <code>StringBuffer</code>, or the <code>null</code> constant
320      *         if any error has occurred.
321      * @throws IOException
322      *             if any exception occurs while reading the stream.
323      * @since 1.3.0
324      */
325     public static StringBuffer readStreamIntoStringBuffer(final InputStream stream, final String charsetName)
326             throws IOException {
327         assert stream != null : "stream is null";
328 
329         Reader streamReader = null;
330         if (charsetName == null) {
331             streamReader = new InputStreamReader(stream);
332         } else {
333             streamReader = new InputStreamReader(stream, charsetName);
334         }
335 
336         final StringWriter out = new StringWriter();
337         int b;
338         while ((b = streamReader.read()) != MINUS_ONE_RETURN_CODE) {
339             out.write(b);
340         }
341 
342         return out.getBuffer();
343     }
344 
345     /**
346      * This method writes the following <code>String</code> into the file.
347      *
348      * @param str
349      *            the <code>String</code> to write, must'nt be <code>null</code> .
350      * @param file
351      *            the file to write into, must'nt be <code>null</code>.
352      * @return <code>true</code> if no error have occurred while writing the file,
353      *         <code>false</code> otherwise.
354      * @since 1.3.0
355      */
356     public static boolean writeIntoFile(final String str, final File file) {
357         return writeIntoFile(str, file, false);
358     }
359 
360     /**
361      * This method writes the following <code>String</code> into the file.
362      *
363      * @param str
364      *            the <code>String</code> to write, must'nt be <code>null</code> .
365      * @param file
366      *            the file to write into, must'nt be <code>null</code>.
367      * @param append
368      *            if <code>true</code>, then data will be written to the end of the file rather than
369      *            the beginning.
370      * @return <code>true</code> if no error have occurred while writing the file,
371      *         <code>false</code> otherwise.
372      * @since 1.3.0
373      */
374     public static boolean writeIntoFile(final String str, final File file, final boolean append) {
375         assert str != null : "str is null";
376         assert file != null : "file is null";
377 
378         LOGGER.log(INFO, buildLogString(WRITE_FILE_INFO, file));
379 
380         boolean error = true;
381         FileWriter writer = null;
382 
383         try {
384             writer = new FileWriter(file, append);
385             writer.write(str, 0, str.length());
386             error = false;
387         } catch (final IOException e) {
388             LOGGER.log(SEVERE, buildLogString(WRITE_FILE_ERROR, file), e);
389         } finally {
390             closeCloseable(writer, file);
391         }
392 
393         return error;
394     }
395 
396     /**
397      * This method writes the following <code>String</code> into the file.
398      *
399      * @param str
400      *            the <code>String</code> to write, must'nt be <code>null</code> .
401      * @param path
402      *            the file path to write into, must'nt be <code>null</code>.
403      * @return <code>true</code> if no error have occurred while writing the file,
404      *         <code>false</code> otherwise.
405      * @since 1.3.0
406      */
407     public static boolean writeIntoFile(final String str, final String path) {
408         return writeIntoFile(str, path, false);
409     }
410 
411     /**
412      * This method writes the following <code>String</code> into the file.
413      *
414      * @param str
415      *            the <code>String</code> to write, must'nt be <code>null</code> .
416      * @param pathName
417      *            the file path to write into, must'nt be <code>null</code>.
418      * @param append
419      *            if <code>true</code>, then data will be written to the end of the file rather than
420      *            the beginning.
421      * @return <code>true</code> if no error have occurred while writing the file,
422      *         <code>false</code> otherwise.
423      * @since 1.3.0
424      */
425     public static boolean writeIntoFile(final String str, final String pathName, final boolean append) {
426         assert pathName != null : "pathName is null";
427 
428         return writeIntoFile(str, new File(pathName), append);
429     }
430 
431     /**
432      * Private constructor to prevent from instantiation.
433      *
434      * @since 1.3.0
435      */
436     private FileUtils() {
437         super();
438     }
439 }