Coverage details for base.util.FileUtil

LineHitsSource
1 /*******************************************************************************
2  *InternetCafe is a software solution that helps the management of Cybercafes
3  * according with the ITALIAN DECREE LAW ON ANTI-TERROR MEASURES, 27 JULY 2005.
4  * Copyright (C) 2006 Guido Angelo Ingenito
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  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *******************************************************************************/
20 package base.util;
21  
22 import java.io.File;
23 import java.io.FileInputStream;
24 import java.io.FileOutputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.security.MessageDigest;
28 import java.security.NoSuchAlgorithmException;
29 import java.util.Vector;
30 import java.util.zip.CRC32;
31  
32 import org.apache.log4j.Logger;
33 import org.bouncycastle.util.encoders.Hex;
34  
35 /**
36  * This class provides some basic methods to manage files and folders.
37  *
38  * @author Guido Angelo Ingenito
390 */
400public class FileUtil {
410 
420    private static final transient Logger logger = Logger
43             .getLogger(FileUtil.class.getName());
44  
45     /**
46      * This method computes the specified file occupied space on the HD. If the
47      * input file is a simple file will be returned its size otherwise if the
48      * file is a directory on local HD will be recursivelly computed the
49      * occupied space of subfolders and contained files.
50      *
51      * @param file
520     * The file or directory whose size must be computed.
530     * @return A Byte rappresentation of the file'size.
540     */
550    public static long fileSizeInByte(File file) {
560        long size = 0;
570 
580        if (file.isDirectory()) {
590            File[] filelist = file.listFiles();
600            for (int i = 0; i < filelist.length; i++) {
610                if (filelist[i].isDirectory()) {
620                    size += fileSizeInByte(filelist[i]);
630                } else {
640                    size += filelist[i].length();
650                }
660            }
670        } else
680            size += file.length();
69  
700        return size;
71     }
72  
73     /**
74      * This method computes the specified file occupied space on the HD. If the
75      * input file is a simple file will be returned its size otherwise if the
76      * file is a directory on local HD will be recursivelly computed the
77      * occupied space of subfolders and contained files.
780     *
790     * @param file
80      * The file or directory whose size must be computed.
81      * @return A Kylo Byte rappresentation of the file'size.
82      */
83     public static long fileSizeInKB(File file) {
840        return fileSizeInByte(file) / 1024;
85     }
86  
87     /**
88      * This method computes the specified file occupied space on the HD. If the
89      * input file is a simple file will be returned its size otherwise if the
900     * file is a directory on local HD will be recursivelly computed the
910     * occupied space of subfolders and contained files.
92      *
93      * @param file
94      * The file or directory whose size must be computed.
95      * @return A Mega Byte rappresentation of the file'size.
96      */
97     public static long fileSizeInMB(File file) {
980        return fileSizeInByte(file) / 1048576;
99     }
100  
101     /**
1020     * This method computes the specified file occupied space on the HD. If the
1030     * input file is a simple file will be returned its size otherwise if the
104      * file is a directory on local HD will be recursivelly computed the
105      * occupied space of subfolders and contained files.
106      *
107      * @param file
108      * The file or directory whose size must be computed.
109      * @return A Giga Byte rappresentation of the file'size.
110      */
111     public static long fileSizeInGB(File file) {
1120        return fileSizeInByte(file) / 1073741824;
1130    }
1140 
1150    /**
1160     * This method creates a CRC32 Checksum relative to the file passed as
1170     * formal parameter.
1180     *
1190     * @param file
1200     * The file whose checksum must be created.
1210     * @return The value of the CRC32 checksum-
1220     * @throws IOException
1230     * If can't be created the InputStream associated to the input
1240     * File.
1250     */
126     public static Long createCRC32Checksum(File file) throws IOException {
1270        logger.debug("createCRC32Checksum(" + file.toString() + ")");
128  
1290        InputStream inputStream = new FileInputStream(file);
1300        CRC32 checksum = new CRC32();
1310        checksum.reset();
1320        byte[] buffer = new byte[1024];
133         int bytesRead;
1340        while ((bytesRead = inputStream.read(buffer)) >= 0) {
1350            checksum.update(buffer, 0, bytesRead);
1360        }
1370        inputStream.close();
1380        logger.debug("CRC32 Checksum value: " + checksum.getValue());
1390 
1400        return new Long(checksum.getValue());
141     }
142  
143     /**
144      * This method checks if the computed CRC32 Checksum of the input file is
145      * equals to the provided crc32Checksum passed as formal argument.
146      *
147      * @param file
148      * The file whose checksum must be compared with the input
149      * crc32Checksum.
150      * @param crc32Checksum
151      * The comparation parameter.
1520     * @return True if the computed checksum is queals to the crc32Checksum,
153      * false otherwise.
1540     * @throws IOException
1550     * If can't be created the InputStream associated to the input
1560     * File.
1570     */
1580    public static boolean checkCRC32Checksum(File file, Long crc32Checksum)
1590            throws IOException {
1600        logger.debug("checkCRC32Checksum(" + file.toString() + ","
1610                + crc32Checksum + ")");
1620        Long checksum = createCRC32Checksum(file);
1630        return checksum.equals(crc32Checksum);
164     }
1650 
1660    /**
167      * This method builds an array of files. In the case the passed formal
1680     * parameter named "file" is a simple file it is returned otherwise if it is
169      * a directory all sub-files and sub-directories are navigated recursivelly
170      * and are added to the resultant array.
171      *
172      * @param file
173      * The file or folder from which the resultant array is built.
174      * @return An array of one file if the formal parameter named "file" is a
175      * simple file a list of sub-files or sub-directories built
176      * recursivelly if the formal parameter is a directory.
1770     */
1780    public static File[] allFileContent(File file) {
1790        Vector<File> result = new Vector<File>();
1800 
1810        if (file.isDirectory()) {
1820            File[] filelist = file.listFiles();
1830            for (int i = 0; i < filelist.length; i++) {
1840                if (filelist[i].isDirectory()) {
1850                    File[] content = allFileContent(filelist[i]);
1860                    for (int k = 0; k < content.length; k++)
1870                        result.add(content[k]);
1880                } else {
1890                    result.add(filelist[i]);
190                 }
191             }
1920        } else
1930            result.add(file);
194  
1950        return result.toArray(new File[0]);
196     }
197  
198     /**
1990     * Deletes all files and subdirectories under directory.
2000     *
201      * @param directory
202      * The directory that must be deleted.
2030     * @return True if all deletions were successful. If a deletion fails, the
204      * method stops attempting to delete and returns false.
2050     */
206     public static boolean deleteDirectory(File directory) {
2070        if (directory.isDirectory()) {
2080            String[] children = directory.list();
2090            for (int i = 0; i < children.length; i++) {
2100                File toBeDeleted = new File(directory, children[i]);
2110                logger.debug("Deleting : " + toBeDeleted);
2120                boolean success = deleteDirectory(toBeDeleted);
2130                if (!success) {
2140                    return false;
2150                }
216             }
2170        }
2180        // The directory is now empty so delete it
2190        return directory.delete();
2200    }
221  
222     /**
223      * This method builds an MD5 Digest of a provided input file.
224      *
225      * @param file
226      * The file whose MD5 Digest must be build.
227      * @return The files'MD5 Digest.
228      * @throws IOException
229      * If the method can't use the filesystem or the provided file
230      * doesn't exists.
2310     */
2320    public static String createMD5Digest(File file) throws IOException {
2330        String result = "";
2340        InputStream inputStream = new FileInputStream(file);
235         MessageDigest messageDigest;
236         try {
2370            messageDigest = MessageDigest.getInstance("MD5");
238  
2390            byte[] buffer = new byte[1024];
240             int bytesRead;
2410            while ((bytesRead = inputStream.read(buffer)) >= 0) {
2420                messageDigest.update(buffer, 0, bytesRead);
2430            }
2440            inputStream.close();
2450            result = new String(Hex.encode(messageDigest.digest()));
2460 
2470            logger.debug("The MD5 Digest for: " + file + " is: " + result);
2480 
2490        } catch (NoSuchAlgorithmException ex) {
2500            // TODO Auto-generated catch block
2510            logger.error(ex.getMessage());
2520            ex.printStackTrace();
2530        }
2540        return result;
255     }
2560 
2570    /**
2580     * This method checks if the computed MD5 Digest of the input file is equals
259      * to the provided md5Digest passed as formal argument.
2600     *
2610     * @param file
2620     * The file whose md5 digest must be compared with the input
2630     * md5Digest.
2640     * @param md5Digest
2650     * The comparation parameter.
2660     * @return True if the computed md5 digest is queals to the md5Digest, false
267      * otherwise.
268      * @throws IOException
269      * If can't be created the InputStream associated to the input
270      * File.
271      */
272     public static boolean checkMD5Digest(File file, String md5Digest)
273             throws IOException {
2740        logger.debug("checkMD5Digest(" + file.toString() + "," + md5Digest
275                 + ")");
2760        String digest = createMD5Digest(file);
2770        return digest.equals(md5Digest);
278     }
279  
280     /**
281      * This method reads all the lines of the input file returning its content
282      * in form of a String.
283      *
284      * @param file
285      * The file whose content must be retrieved.
286      * @return The content of the input file.
287      * @throws IOException
288      * If can't work on the filesystem.
289      */
290     public static String fileContent(File file) throws IOException {
2910        StringBuffer result = new StringBuffer();
2920        FileInputStream inputStream = new FileInputStream(file);
2930        byte[] buffer = new byte[1024];
294         // Read in the decrypted bytes and write the cleartext to out
2950        int numRead = 0;
2960        while ((numRead = inputStream.read(buffer)) >= 0) {
2970            result.append(new String(buffer).toCharArray(), 0, numRead);
298             // outputStream.write(buffer, 0, numRead);
2990        }
3000        return result.toString();
301     }
302  
303     public static void copyFile(File input, File output) throws IOException {
3040        FileInputStream inputStream = new FileInputStream(input);
3050        FileOutputStream outputStream = new FileOutputStream(output);
3060        byte[] buffer = new byte[1024];
307         // Read in the decrypted bytes and write the cleartext to out
3080        int numRead = 0;
3090        while ((numRead = inputStream.read(buffer)) >= 0) {
3100            outputStream.write(buffer, 0, numRead);
3110        }
3120        inputStream.close();
3130        outputStream.close();
3140    }
315 }

this report was generated by version 1.0.5 of jcoverage.
visit www.jcoverage.com for updates.

copyright © 2003, jcoverage ltd. all rights reserved.
Java is a trademark of Sun Microsystems, Inc. in the United States and other countries.