package divconq.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class IOUtil {
    /**
     * Try to remove all folders and files from a given path.
     * Then remove the folder itself.
     * 
     * @param path path to folder to remove
     */
    public static void deleteRecursive(File path) {
        if (!path.exists()) 
        	return;
        
        if (path.isDirectory())
            for (File f : path.listFiles())
                IOUtil.deleteRecursive(f);

        path.delete();
    }
    
    /**
     * Read entire text file into a string.
     * 
     * @param file to read
     * @return file content if readable, otherwise null
     */
    public static String readEntireFile(File file) {
    	BufferedReader br = null;
    	
        try {
            StringBuilder sb = new StringBuilder();
            
        	br = new BufferedReader(new FileReader(file));
        	
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append("\n");
                line = br.readLine();
            }
            
            return sb.toString();
        } 
        catch (IOException x) {
		} 
        finally {
        	if (br != null)
				try {
					br.close();
				} 
        		catch (IOException x) {
        			// ignore
				}
        }
        
        return null;
    }
}
