Anda di halaman 1dari 6

1

I/O Streams
An I/O Stream represents an input source or an output destination. A stream can represent many different
kinds of sources and destinations, including disk files, devices, other programs, and memory arrays.
Streams support many different kinds of data, including simple bytes, primitive data types, localized
characters, and objects. Some streams simply pass on data; others manipulate and transform the data in
useful ways.
No matter how they work internally, all streams present the same simple model to programs that use them:
A stream is a sequence of data. A program uses an input stream to read data from a source, one item at a
time:

Reading information into a program.
A program uses an output stream to write data to a destination, one item at time:

Writing information from a program.
Streams can handle all kinds of data, from primitive values to advanced objects.
The data source and data destination pictured above can be anything that holds, generates, or consumes data.
Obviously this includes disk files, but a source or destination can also be another program, a peripheral
device, a network socket, or an array.
Character Streams
The Java platform stores character values using UNICODE conventions. Character stream I/O automatically
translates this internal format to and from the local character set. In Western locales, the local character set is
usually an 8-bit superset of ASCII.
For most applications, I/O with character streams is no more complicated than I/O with byte streams. Input
and output done with stream classes automatically translates to and from the local character set. A program
that uses character streams in place of byte streams automatically adapts to the local character set and is
ready for internationalization all without extra effort by the programmer.
2
All character stream classes are descended from the classes Reader and Writer.
Character Streams that Use Byte Streams: There are two general-purpose byte-to-character "bridge"
streams: InputStreamReader and OutputStreamWriter.
The 3 streams System.in, System.out, and System.err are also common sources or destinations of data.
Most commonly used is probably System.out for writing output to the console from console programs.
These 3 streams are initialized by the Java runtime when a JVM starts up, so you don't have to instantiate
any streams yourself (although you can exchange them at runtime).
Buffered Streams
The Java platform implements buffered I/O streams. Buffered input streams read data from a memory area
known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output
streams write data to a buffer, and the native output API is called only when the buffer is full.
A program can convert an unbuffered stream into a buffered stream using the wrapping idiom (property),
where the unbuffered stream object is passed to the constructor for a buffered stream class. There are four
buffered stream classes used to wrap unbuffered streams: BufferedInputStream and
BufferedOutputStream create buffered byte streams, while BufferedReader and
BufferedWriter create buffered character streams.
Flushing Buffered Streams
It often makes sense to write out a buffer at critical points, without waiting for it to fill. This is known as
flushing the buffer.
Some buffered output classes support autoflush, specified by an optional constructor argument. When
autoflush is enabled, certain key events cause the buffer to be flushed. For example, an autoflush
PrintWriter object flushes the buffer on every invocation of println or format. The print and
println format individual values in a standard way.
Class: BufferedReader
Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of
characters, arrays, and lines.
The buffer size may be specified, or the default size may be used. The default is large enough for most
purposes.
In general, each read request made of a Reader causes a corresponding read request to be made of the
underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader
whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,
BufferedReader in
= new BufferedReader(new InputStreamReader(System.in));

will buffer the input from the specified console input System.in.


3
Class: InputStreamReader
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them
into characters using a specified charset. The charset that it uses may be specified by name or may be
given explicitly, or the platform's default charset may be accepted.
System.in
System.in is an InputStream which is typically connected to keyboard input of console programs.
System.in is not used as often since data is commonly passed to a command line Java application via
command line arguments, or configuration files. In applications with GUI the input to the application is
given via the GUI. This is a separate input mechanism from Java IO.
System.out
System.out is a PrintStream. System.out normally outputs the data you write to it to the console. This is
often used from console-only programs like command line tools. This is also often used to print debug
statements of from a program (though it may arguably not be the best way to get debug info out of a
program).
System.err
System.err is a PrintStream. System.err works like System.out except it is normally only used to
output error texts. Some programs (like Eclipse) will show the output to System.err in red text, to make it
more obvious that it is error text.
Each invocation of one of an InputStreamReader's read() methods may cause one or more bytes to be read
from the underlying byte-input stream. To enable the efficient conversion of bytes to characters, more bytes
may be read ahead from the underlying stream than are necessary to satisfy the current read operation.
For top efficiency, consider wrapping an InputStreamReader within a BufferedReader. For example:
BufferedReader in
= new BufferedReader(new InputStreamReader(System.in));

The print and println Methods
Invoking print or println outputs a single value after converting the value using the appropriate
toString method. We can see this in the Root example:
public class Root {
public static void main(String[] args) {
int i = 2;
double r = Math.sqrt(i);
System.out.print("The square root of ");
System.out.print(i);
System.out.print(" is ");
System.out.print(r);
System.out.println(".");
i = 5;
r = Math.sqrt(i);
System.out.println("The square root of " + i + " is " + r + ".");
}
}
4
Here is the output of Root:
The square root of 2 is 1.4142135623730951.
The square root of 5 is 2.23606797749979.
The i and r variables are formatted twice: the first time using code in an overload of print, the second
time by conversion code automatically generated by the Java compiler, which also utilizes toString.
You can format any value this way, but you don't have much control over the results.

Line-Oriented I/O
Character I/O usually occurs in bigger units than single characters. One common unit is the line: a string of
characters with a line terminator at the end. A line terminator can be a carriage-return/line-feed sequence
("\r\n"), a single carriage-return ("\r"), or a single line-feed ("\n"). Supporting all possible line
terminators allows programs to read text files created on any of the widely used operating systems.
To use line-oriented I/O we have to use the class: BufferedReader.
import java.io.*;
public class BufferedReaderStream
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader (System.in));

String strLine; // declare a String variable

System.out.println ("Enter any text: "); // prompt for input
strLine = br.readLine(); //Read a line of text

// Print the content on the console
System.out.println ("You entered : " +strLine);
}
}
The example invokes BufferedReader.readLine to do input one line at a time.
Invoking readLine returns a line of text with the line and outputs the line using println, which
appends the line terminator for the current operating system.

5
Read interactive command-line input with Java
Introduction - Reading Java command line input

While Java is generally used to create applets, servlets, and general-purpose applications, you may
occasionally need to create applications that interactively communicate with a user at a command-line
prompt, such as a Unix or DOS prompt. In these cases you normally see a prompt like this:

Enter your name: _

While reading command line input is often the domain of scripting languages, you may want to use
Java for this purpose to take advantage of how easy it is to accomplish most tasks with Java -
especially networking and database access.

Unfortunately, this is one area where it's difficult to use vanilla Java methods. If you're used to simple
echo and read statements in shell scripts, you're in for a bit of shock. I suspect the creators of Java
didn't expect to see their language used for this purpose, or they just assumed developers would
create their own classes to simplify this process.

In this article we'll present a technique we use when creating Java programs that require interactive
command-line input. If you like this basic technique, and would like to see expanded coverage of how
to read numeric values, or would like to see a custom class for handling command-line input, just
leave a comment below, and we'll provide a follow-up as quickly as we can.
Reading a string the user enters at a command-line prompt

The basic technique of reading a String provided by a user at a command-line is fairly simple, but
more lengthy than you'd expect. It involves the use of the System.in object, along with the
InputStreamReader and BufferedReader classes.

The code in Listing 1 shows how you can prompt the user to enter a String value, such as their name,
and then read that value:

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

System.out.print("Enter your name: "); // prompt the user to enter their name

// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String userName = null;

// read the username from the command-line; need to use try/catch with the readLine() method
try {
userName = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your name!");
System.exit(1);
}
System.out.println("Thanks for the name, " + userName);
}
} // end of ReadString class
6
Listing 1: The ReadString.java program shows how you can prompt the user to enter their name, and
then read the name into the userName variable.

Listing 1 demonstrates how you can print a prompt to the user using the System.out.print() method.
Notice that we use the print() method instead of println(). Using the print() method lets us keep the
cursor on the same line of output as our printed text. This makes it look like a real prompt (instead of
having the user's response appear on the line below our prompt).

Next, we read the user's input by passing the System.in object to the InputStreamReader and then into
the BufferedReader The Java BufferedReader class gives us the readLine() method, and applies
buffering to the input character input stream. Notice that the readLine() method can thrown an
IOException error, so we have to enclose the statement in a try/catch statement.

Anda mungkin juga menyukai