Like the title says, im trying to write a program that can read individual words from a text file and store them to String
variables. I know how to use a
You must use StringTokenizer! here an example and read this String Tokenizer
private BufferedReader innerReader;
public void loadFile(Reader reader)
throws IOException {
if(reader == null)
{
throw new IllegalArgumentException("Reader not valid!");
}
this.innerReader = new BufferedReader(reader);
String line;
try
{
while((line = innerReader.readLine()) != null)
{
if (line == null || line.trim().isEmpty())
throw new IllegalArgumentException(
"line empty");
//StringTokenizer use delimiter for split string
StringTokenizer tokenizer = new StringTokenizer(line, ","); //delimiter is ","
if (tokenizer.countTokens() < 4)
throw new IllegalArgumentException(
"Token number not valid (<= 4)");
//You can change the delimiter if necessary, string example
/*
Hello / bye , hi
*/
//reads up "/"
String hello = tokenizer.nextToken("/").trim();
//reads up ","
String bye = tokenizer.nextToken(",").trim();
//reads up to end of line
String hi = tokenizer.nextToken("\n\r").trim();
//if you have to read but do not know if there will be a next token do this
while(tokenizer.hasMoreTokens())
{
String mayBe = tokenizer.nextToken(".");
}
}
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}