package tiedosto; import java.io.*; import fi.jyu.mit.ohj2.Mjonot; /** * Lukujen lukeminen tiedostosta * @author Vesa Lappalainen * @version 1.0, 07.03.2003 */ public class TiedKa { /** * Testataan tiedoston lukemista * @param args ei käytössä */ public static void main(String[] args) { BufferedReader fi; try { // Avataan tiedosto lukemista varten fi = new BufferedReader(new FileReader("luvut.dat")); } catch (FileNotFoundException ex) { System.err.println("Tiedosto ei aukea!"); return; } double summa=0; int n=0; try { String s; double luku; while ( ( s = fi.readLine() ) != null ) { try { luku = Double.parseDouble(s); summa += luku; n++; } catch (NumberFormatException ex) { } } } catch (IOException ex) { System.err.println("Virhe tiedostoa luettaessa!"); } finally { // Aina ehdottomasti finally:ssa resurssien vapautus try { fi.close(); // tiedoston sulkeminen heti kun sitä ei enää tarvita } catch (IOException ex) { System.err.println("Tiedostoa ei saa suljettua!"); } } double ka = 0; if ( n > 0 ) ka = summa/n; System.out.println("Lukuja oli " + n + " kappaletta."); System.out.println("Niiden summa oli " + Mjonot.fmt(summa,4,2)); System.out.println("ja keskiarvo oli " + Mjonot.fmt(ka,4,2)); } }