CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Sep 2008
    Posts
    49

    How would i add a tokenizer to this code?

    I have had experience with tokenizers, but not sure how to add it to the following piece of code... can anyone help?

    Code:
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileNotFoundException;
    import java.io.IOException;
     
    public class ReadTextFileExample
    {
    	
    	public void getScore()
    	{
    		File file = new File("scores.txt");
    		StringBuffer contents = new StringBuffer();
    		BufferedReader reader = null;
    		
    		try
    		{
    			reader = new BufferedReader(new FileReader(file));
    			String text = null;
    			
    			//repeat ten times.
    			
                while ((text = reader.readLine()) != null)
    			{
    				contents.append(text).append(System.getProperty("line.separator"));
    			}
    		}
    		catch(FileNotFoundException e)
    		{
    			e.printStackTrace();
    		}
    		catch(IOException e)
    		{
    			e.printStackTrace();
    		}
    		finally
    		{
                try
                {
                    if (reader != null)
                    {
                        reader.close();
                    }
                } 
                
                catch (IOException e)
                {
                    e.printStackTrace();
                }
    		}
    		
    		// show file contents here
            System.out.println(contents.toString());
    		}
    	}
    The code gives the following output...

    Code:
    John 5000
    Lewis 3000
    Eamon 2000
    Leam 1000
    the reason i need to use tokenizers, is to separate the names, and scores... thanks...

  2. #2
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: How would i add a tokenizer to this code?

    If you mean StringTokenizer, then I recommend that you don't use it. Sun have declared it a legacy class (though, oddly, not deprecated) and suggest that String.split(..) is used, or classes in the java.util.regex package.

    If the delimiter is a space, text.split(" ") will give you an array of the delimited tokens.

    Scientists build to learn; Engineers learn to build...
    F. Brooks
    Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured