Instructional Objectives
After participating in this practicum, students are expected to be able to:
- Understanding the use of streams.
- Create a stream utilization program.
1. Stream
Streams are used to handle I/O processes in Java. Input streams are used to read data and output streams are used to write data. Different stream classes, such as java.io.FileInputStream and sun.net.TelnetOutputStream, are used to read and write specific data sources. However, all output streams have the same basic method for writing data and input streams use the same basic method for reading data.
Subclasses of OutputStream use methods to write data to a specific medium. For example, FileOutputStream uses this method to write data to a file. The basic method of OutputStream is write(int b). This method takes an integer from 0 to 255 as an argument and writes the corresponding bytes to the output stream.
Subclasses of InputStream use these methods to read data from a specific medium. For example, a FileInputStream reads data from a file. A TelnetInputStream reads data from a network connection. A ByteArrayInputStream reads data from a byte array. The basic method of InputStream is the noargs() method. This method reads one byte of data from the source input stream and returns it as an int from 0 to 255.
2. Reader and Writer
The most important subclasses of Reader and Writer are the InputStreamReader and OutputStreamWriter classes. An InputStreamReader contains an underlying input stream from which it reads raw bytes. It translates these bytes into Unicode characters according to a particular encoding. An OutputStreamWriter receives Unicode characters from a running program. It then translates those characters into bytes using a particular encoding and writes the bytes to the underlying output stream.
In addition to these two classes, the java.io package provides several default reader and writer classes that read characters without directly requiring the underlying input stream, including:
- FileReader
- FileWriter
- StringReader
- StringWriter
- CharArrayReader
- CharArrayWriter
3. Example Program
Listing 2.1
import java.io.*;
class input1 {
public static void main(String[] args) throws IOException {
String str;
BufferedReader br;
br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Masukkan Nama Anda : ");
str= br.readLine();
System.out.println("Hello "+ str);
}
}
Listing 2.2
import java.io.*;
class input2 {
public static void main(String[] args) throws IOException {
nt angka1, angka2;
BufferedReader br;
br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Masukkan Angka1 : ");
angka1 = Integer.parseInt(br.readLine());
System.out.print("Masukkan Angka2 : ");
angka2 = Integer.parseInt(br.readLine());
System.out.println("Angka1 Anda : "+ angka1);
System.out.println("Angka2 Anda : "+ angka2);
}
}