001    /*
002     *  Copyright (C) 2003 Adam Olsen
003     *  This program is free software; you can redistribute it and/or modify
004     *  it under the terms of the GNU General Public License as published by
005     *  the Free Software Foundation; either version 1, or (at your option)
006     *  any later version.
007     *  This program is distributed in the hope that it will be useful,
008     *  but WITHOUT ANY WARRANTY; without even the implied warranty of
009     *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
010     *  GNU General Public License for more details.
011     *  You should have received a copy of the GNU General Public License
012     *  along with this program; if not, write to the Free Software
013     *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
014     */
015    package com.valhalla.misc;
016    
017    import java.io.ByteArrayOutputStream;
018    import java.io.File;
019    import java.io.OutputStreamWriter;
020    
021    /**
022     * Miscellaneous tools good for any application
023     * 
024     * @author synic
025     * @created November 30, 2004
026     */
027    public class MiscUtils {
028        /**
029         * Deletes a directory, and all the files in it
030         * 
031         * @param dir
032         *            the directory to delete
033         * @exception Exception
034         *                thrown if there is an error deleting the dir
035         */
036        public static void recursivelyDeleteDirectory(String dir) throws Exception {
037            File file = new File(dir);
038            if (!file.isDirectory() || !file.exists()) {
039                throw new Exception(dir
040                        + " was not a directory, could not recursively delete it");
041            }
042    
043            File[] files = file.listFiles();
044            for (int i = 0; i < files.length; i++) {
045                if (files[i].isDirectory()) {
046                    recursivelyDeleteDirectory(files[i].getPath());
047                } else {
048                    if (!files[i].delete()) {
049                        throw new Exception("Could not delete " + files[i] + ".");
050                    }
051                }
052            }
053    
054            if (!file.delete()) {
055                throw new Exception("Could not delete " + file + ".");
056            }
057        }
058    
059        /**
060         * Gets stream encoding
061         * 
062         * @return stream encoding.
063         */
064        public static String streamEncoding() {
065            OutputStreamWriter out = new OutputStreamWriter(
066                    new ByteArrayOutputStream());
067            return out.getEncoding();
068        }
069    }
070