|
-
April 28th, 2009, 07:52 AM
#1
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...
-
April 28th, 2009, 08:52 AM
#2
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|