/** * --Copyright notice-- * * Copyright (c) School of Geography, University of Leeds. * http://www.geog.leeds.ac.uk/ * This software is licensed under 'The Artistic License' which can be found at * the Open Source Initiative website at... * http://www.opensource.org/licenses/artistic-license.php * Please note that the optional Clause 8 does not apply to this code. * * The Standard Version source code, and associated documentation can be found at... * [online] http://mass.leeds.ac.uk/ * * * --End of Copyright notice-- * */ import java.io.*; import java.util.*; import java.awt.*; /** * Reads and writes file data. * @version 1.0 * @author Andy Evans */ public class IO { /** * Reads an array of doubles from a text file. * File delimiters are commas and spaces. * @param f text file to read * @return data read in */ public double[][] readData(File f) { // Count lines FileReader fr = null; try { fr = new FileReader (f); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } BufferedReader br = new BufferedReader(fr); int lines = -1; String textIn = " "; String[] file = null; try { while (textIn != null) { textIn = br.readLine(); lines++; } file = new String[lines]; br.close(); try { fr = new FileReader (f); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } // Read lines. br = new BufferedReader(fr); for (int i = 0; i < lines; i++) { file[i] = br.readLine(); } br.close(); } catch (IOException ioe) {} // Convert lines to doubles. double[][] data = new double [lines][]; for (int i = 0; i < lines; i++) { StringTokenizer st = new StringTokenizer(file[i],", "); data[i] = new double[st.countTokens()]; int j = 0; while (st.hasMoreTokens()) { data[i][j] = Double.parseDouble(st.nextToken()); j++; } } return data; } /** * Write an array of doubles to a text file. * Data delimiter is commas and space. * @param dataIn data to write * @param f text file to write */ public void writeData(double[][] dataIn, File f) { FileWriter fw = null; try { fw = new FileWriter (f, false); } catch (IOException ioe) { ioe.printStackTrace(); } BufferedWriter bw = new BufferedWriter (fw); String tempStr = ""; try { for (int i = 0; i < dataIn.length; i++) { for (int j = 0; j < dataIn[i].length; j++) { tempStr = String.valueOf(dataIn[i][j]); bw.write(tempStr + ", "); } bw.newLine(); } bw.close(); } catch (IOException ioe) {} } }