Reading Numbers from a Text File : Java examples (example source code) » File Input Output » File Reader

Java
C++
Java Products
Java Articles
Java Home  »   File Input Output   » [  File Reader  ]  Screenshots 
 



Reading Numbers from a Text File

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StreamTokenizer;

// The buffering makes the program more than 20 times faster.
public class SumFile {

  public static void main(String[] athrows IOException {
      sumfile("file.txt");
  }


  static void sumfile(String filenamethrows IOException {
    Reader r = new BufferedReader(new FileReader(filename));
    StreamTokenizer stok = new StreamTokenizer(r);
    stok.parseNumbers();
    double sum = 0;
    stok.nextToken();
    while (stok.ttype != StreamTokenizer.TT_EOF) {
      if (stok.ttype == StreamTokenizer.TT_NUMBER)
        sum += stok.nval;
      else
        System.out.println("Nonnumber: " + stok.sval);
      stok.nextToken();
    }
    System.out.println("The file sum is " + sum);
  }

}
Related examples in the same category
1.  Reading Numbers from a Text File, Line by Line
2.  Indent - prepend leading spaces
3.  Read a file and print, using BufferedReader and System.out
4.  Open File By Name
5.  Read a file containing an offset, and a String at that offset
6.  Testing for end of file while reading a byte at a time Testing for end of file while reading a byte at a time
7.  File Locking File Locking
8.  Getting channels from streams








Home| Contact Us
Copyright 2003 - 04 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.