Link to home
Start Free TrialLog in
Avatar of javanewbie
javanewbie

asked on

reading strings

hi, im writing a program that has to ouput all the words in a text file seperately. so for example if in the text file there was a line with the words "today is monday" then the output would be:
today
is
monday

the code i have so far is as follows:

// IODemoClass.java

import java.io.*;
public class IODemoClass
{
     
     public static void main (String[] args) throws IOException, ClassNotFoundException
     {
          // For J++: to keep the application window open
          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         

          testString("textfile.txt");
         
          String wait = br.readLine();
     } // end main()
     
     

     public static void testString(String fileName) throws IOException, FileNotFoundException {
         

         
          // now open the file and create a buffer object that can
          // be used to read the text from the stream
          FileReader fr = new FileReader(fileName);
          BufferedReader fbr = new BufferedReader(fr);

          String current = null;
          int total = 0;
          while (fbr.ready()) {  // while there is more text to read from fr
               current = fbr.readLine();  // read the next line from the file
               total++;
          }
          fbr.close(); // closes the buffered reader and the connected file.
          System.out.println(total + " lines read from file " + fileName);
     } // end testInt()

} // end class


what this dies is opens the file and output the number of lines in the file. can anyone help me so that the program now outputs all the words within the file?
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

OK. What you need to do here is two things:

1. Read the file line by line
2. 'Tokenize' the line so that each word is separated from the other and printed on its own line.

Give me a minute...
import java.io.*;
import java.util.StringTokenizer;

public class TokenizeLine {

  public static void main(String[] args){
    if(args.length < 1){
     System.out.println("Usage: java TokenizeLine <file to tokenize>");
     System.exit(-1);
    }
    BufferedReader in = null;
    String fileLine = null;
    try {
      in = new BufferedReader(new FileReader(args[0]));
      while ((fileLine = in.readLine()) != null){
        StringTokenizer st = new StringTokenizer(fileLine);
        while (st.hasMoreTokens()){
          System.out.println(st.nextToken());
        }
      }
    }
    catch (IOException e){
      e.printStackTrace();
    }
    finally {
      try { in.close(); } catch(IOException e) { e.printStackTrace(); }
    }

  }

}
Avatar of javanewbie
javanewbie

ASKER

how does this work with the code i have already wrote? thanks for your help! :)
Well it just demos what to do. How do you want the program to work - do you want it to read the name of the file in question from the command line?
how does this work with the code i have already wrote? thanks for your help! :)
oops double post. when i run the code i wrote myself it outputs in a console window the number of lines in the text file that i have given in my code. this time i want it to list all the words in that file.
Just replace your main() method with mine, but before

BufferedReader = null;

put

args[0] = "textfile.txt";
Don't forget

import java.util.StringTokenizer;

that goes at the top of your code

You can then get rid of the testString() method
when i execute it i get an error message saying:

exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at IODemoClass.main

am i right in saying that the code i should use would be:

// IODemoClass.java
import java.util.StringTokenizer;
import java.io.*;
public class IODemoClass
{
     
 public static void main(String[] args){
   
   if(args.length < 1){
    System.out.println("Usage: java TokenizeLine <textfile.txt>");
    System.exit(-1);
   }
   args[0] = "textfile.txt";
   BufferedReader in = null;
   String fileLine = null;
   try {
     in = new BufferedReader(new FileReader(args[0]));
     while ((fileLine = in.readLine()) != null){
       StringTokenizer st = new StringTokenizer(fileLine);
       while (st.hasMoreTokens()){
         System.out.println(st.nextToken());
       }
     }
   }
   catch (IOException e){
     e.printStackTrace();
   }
   finally {
     try { in.close(); } catch(IOException e) { e.printStackTrace(); }
   }

 }

}
Sorry, take out

if(args.length < 1){
   System.out.println("Usage: java TokenizeLine <textfile.txt>");
   System.exit(-1);
  }
im still getting the same error. thanks for helping me! :D
This works perfectly for me:

import java.io.*;
import java.util.StringTokenizer;

public class TokenizeLine {

  public static void main(String[] args){
    args[0] = "textfile.txt";
    BufferedReader in = null;
    String fileLine = null;
    try {
      in = new BufferedReader(new FileReader(args[0]));
      while ((fileLine = in.readLine()) != null){
        StringTokenizer st = new StringTokenizer(fileLine);
        while (st.hasMoreTokens()){
          System.out.println(st.nextToken());
        }
      }
    }
    catch (IOException e){
      e.printStackTrace();
    }
    finally {
      try { in.close(); } catch(IOException e) { e.printStackTrace(); }
    }

  }

}
If that doesn't work, remove

args[0] = "textfile.txt";

and change


in = new BufferedReader(new FileReader(args[0]));

to


in = new BufferedReader(new FileReader("textfile.txt"));

hey! thanks! i got it working! just another quick question! how do i got the commas and full stops not to show? is it easy to get the list of words to appear in alphabetical order?
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
a great help! thanks! :D