PDA

View Full Version : Buffer Reader help.


imperialsanctum
02-04-2010, 12:10 AM
Hey I am relitively new to Java and seem to be experiencing a problem with the following code:


import java.util.*;
import java.io.*;
public class TestReader {
public static void main(String[] args){

BufferedReader read = new BufferedReader(new FileReader("input.txt"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
StringTokenizer load = new StringTokenizer(read.readLine());

String name1 = load.nextToken();
String name2 = load.nextToken();

out.println(name1 + name2);

}
}

The file input.txt simply contains:

John
Peter

Could anyone explain what is causing the error? Thanks in advance :D

brad211987
02-04-2010, 12:27 AM
Hey I am relitively new to Java and seem to be experiencing a problem with the following code:


import java.util.*;
import java.io.*;
public class TestReader {
public static void main(String[] args){

BufferedReader read = new BufferedReader(new FileReader("input.txt"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
StringTokenizer load = new StringTokenizer(read.readLine());

String name1 = load.nextToken();
String name2 = load.nextToken();

out.println(name1 + name2);

}
}

The file input.txt simply contains:

John
Peter

Could anyone explain what is causing the error? Thanks in advance :D

whats the problem?

imperialsanctum
02-04-2010, 12:29 AM
whats the problem?

Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:332)
at ride.main(ride.java:16)

I think it's because it only reads the first line of the "input.txt" file, but I have no idea on how to fix it.

brad211987
02-04-2010, 12:31 AM
Looks to me like you only read the first line, but tried to pull both tokens off of it. Each line only has one token.

try calling read.readLine() again and assigning it to a new tokenizer. Or you should be able to skip the tokenizer all together, as your not really splitting any strings.

You could do something like:

String first = read.readLine().trim();
String last = read.readLine().trim();

imperialsanctum
02-04-2010, 12:33 AM
Looks to me like you only read the first line, but tried to pull both tokens off of it. Each line only has one token.

try calling read.readLine() again and assigning it to a new tokenizer. Or you should be able to skip the tokenizer all together, as your not really splitting any strings.

You could do something like:

String first = read.readLine().trim();
String last = read.readLine().trim();

Oh! Thanks, it worked.