System.out is a PrintStream object that outputs to the screen
System.in is an InputStream object that reads from the keyboard
But System.in doesn't have methods to read a line directly. There is a method
called readLine that does, but it is defined on BufferedReader objects.
- How do we construct a BufferedReader? One way is with an InputStreamReader.
- How do we construct an InputStreamReader? We need an InputStream.
- How do we construct an InputStream? System.in is one.
(You can figure all of this out by looking at the constructors in the online
Java libraries API--specifically, in the java.io library.)
InputStream objects (e.g. System.in) read raw data from some source (like Keyboard), but don't format the data.
InputStreamReader objects compose the raw data into characters (2 bytes long in Java).
BufferedReader objects compose the characters into entire lines of text.
Java program that reads a line from the keyboard and prints it on the screen.
import java.io.*; class SimpleIO { public static void main(String[] args) throws Exception { BufferedReader keybd = new BufferedReader(new InputStreamReader(System.in)); System.out.println(keybd.readLine()); } }
How to read a line of text: With readLine on BufferedReader
How to create a BufferedReader: With an InputStreamReader
How to create a InputStreamReader: With an InputStream
How to create InputStream: With a URL
public class BufferedReader extends Reader
BufferedReader is a class
Code:
import java.net.*; import java.io.*; class WHWWW { public static void main(String[] arg) throws Exception { URL u = new URL("http://www.whitehouse.gov/"); InputStream ins = u.openStream(); InputStreamReader isr = new InputStreamReader(ins); BufferedReader whiteHouse = new BufferedReader(isr); System.out.println(whiteHouse.readLine()); } }
No comments:
Post a Comment