FileIO.java

package ac.essex.ooechs.imaging.commons.util; 
 
import java.io.*; 
import java.net.URL; 
 
/** 
 * <p/> 
 * This program is free software; you can redistribute it and/or 
 * modify it under the terms of the GNU General Public License 
 * as published by the Free Software Foundation; either version 2 
 * of the License, or (at your option) any later version, 
 * provided that any use properly credits the author. 
 * This program is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 * GNU General Public License for more details at http://www.gnu.org 
 * </p> 
 * 
 * @author Olly Oechsle, University of Essex, Date: 22-Jun-2007 
 * @version 1.0 
 */ 
public class FileIO { 
 
    public static String readFile(File f) throws IOException { 
 
        StringBuffer buffer = new StringBuffer(); 
 
        /* Filter FileReader through a Buffered read to read a line at a time */ 
        BufferedReader bufRead = new BufferedReader(new FileReader(f)); 
 
        // Read the first line 
        String line = bufRead.readLine(); 
 
        // Read through file one line at time. 
        while (line != null) { 
            buffer.append(line); 
            buffer.append("\n"); 
            line = bufRead.readLine(); 
        } 
 
        // close the file 
        bufRead.close(); 
 
        return buffer.toString(); 
    } 
 
    public static void saveToFile(String text, File f) throws IOException { 
        BufferedWriter out = new BufferedWriter(new FileWriter(f)); 
        out.write(text); 
        out.close(); 
    } 
 
    public static void saveFromWeb(String httpURL, File saveAs) { 
 
        try { 
 
            // create the url 
            URL url = new URL(httpURL); 
            InputStream in = url.openStream(); 
            FileOutputStream out = new FileOutputStream(saveAs); 
 
            byte[] b = new byte[1024]; 
            int len; 
            while ((len = in.read(b)) != -1) { 
                out.write(b, 0, len); 
            } 
            out.close(); 
 
            System.out.println("Saved: " + saveAs.getName()); 
 
        } catch (FileNotFoundException fe) { 
            System.err.println("File Not Found: " + httpURL); 
        } catch (Exception e) { 
            System.err.println("Exception caught: " + e.getMessage()); 
        } 
    } 
 
}