Java I/O How to - Split the strings in a file and read them








Question

We would like to know how to split the strings in a file and read them.

Answer

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.StreamTokenizer;
/*from   w w w.j av a  2 s  .  c  o m*/
public class Main {

  public static void main(String[] args) throws Exception {
    BufferedReader in = null;
    in = new BufferedReader(new FileReader("fileeditor.txt"));
    StreamTokenizer st = new StreamTokenizer(in);
    st.eolIsSignificant(false);
    // remove comment handling
    st.slashSlashComments(false);
    st.slashStarComments(false);

    while (st.nextToken() != StreamTokenizer.TT_EOF) {
      if (st.ttype == StreamTokenizer.TT_NUMBER) {
        // the default is to treat numbers differently than words
        // also the numbers are doubles
        System.out.println((int) st.nval);
      } else {
        System.out.println(st.sval);
      }
    }
  }
}