How to tell BufferedReader to stop reading from System.in?
I am using bufferedReader to read System.in from the user, The user will enter a domain address and source address separated by a space.
eg
auckland.ac.nz. 198.19.20.44
www.esc.auckland.ac. 173.27.28.93
stat.auckland.ac.nz. 52.159.152.105
student.auckland.ac.nz. 64.247.240.232
Now the problem is that once the user finishes entering the data, the input stream does not terminate and hence the program does not get executed. I have written some code for the BufferedReader if anyone is willing to check it and tell me where I went wrong I would greatly appreciate it. 开发者_开发百科Notice the two variables "count" and "n", is there anyway I can use those to help with that?
try {
String fqdn, src, key, temp;
Integer count;
int n = 0;
while ((temp = br.readLine()) != null){
int divide = temp.indexOf(" ");
fqdn = temp.substring(0, divide); // divide the input
src = temp.substring(divide+1);
key = fqdn + " " + src;
//System.out.printf("%d: %s\n", n, key);
dht.lookup(key);
n += 1;
}
br.close();
} catch (NoSuchElementException e) {
//System.out.printf("end-of-file\n");
}
The loop will terminate when readLine()
returns null
. The only way that this will happen is if standard input it closed. The user can do this by typing Ctrl+D, but that's perhaps too much to ask from a typical user. One easy alternative is to ask them to type "done" when they're done; then your loop should check for that value, rather than null
.
What I would look at is Observer Pattern
http://en.wikipedia.org/wiki/Observer_pattern and multitreading releated things such as wait()
- use this link: How can I set a timeout against a BufferedReader based upon a URLConnection in Java?
and take a look here: http://www.javaspecialists.eu/archive/Issue153.html
精彩评论