| Lesson 4 | Data streams |
| Objective | Data streams use Java-defined data types |
DataInputStreams and DataOutputStreams have additional methods for reading data types. That is, instead of reading and writing bytes, they can read and write the data types defined by Java. DataInputStream and DataOutputStream are created based on an underlying stream. The idea is that these streams are piped. An instance of DataInputStream, for example, is tied to an instance of class InputStream.
The InputStream subclass reads the individual bytes; DataInputStream assembles them into Java's data types.
readInt() method on the DataInputStream instance.DataInputStream class is a wrapper over InputStream.InputStream and interprets them as an int.InputStream class is the lower-level stream providing the actual data.DataInputStream reads from this raw byte stream.InputStream ultimately gets data from a resource (e.g., a file, network socket, or other byte-based source).InputStream to DataInputStream and finally get converted into an int in your code.readInt() on DataInputStream.InputStream.int.DataInputStream, you tie it to some other subclass of class InputStream. DataInputStream instance tied to the standard input, you can write:
DataInputStream stream = new DataInputStream(System.in);
DataInputStream methods, such as readInt(), which reads 4 bytes and assembles them into an int value. In Java 1.1, reading character-based data is handled by subclasses of Reader class.
To read text a line at a time, the recommended method is the readLine() method of BufferedReader class.
The bridge between InputStream and BufferedReader is InputStreamReader:
InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String s = br.readLine();
readLine() call in a try/catch block in case it throws an IOException.) BufferedReader when we discuss the net package, coming up in the next module.
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
public class InputStreamReaderDemo {
public static void main(String[] args) throws IOException {
InputStream inputStream = new FileInputStream("c:\\input.txt");
Reader reader = new InputStreamReader(inputStream);
int data = 0;
try {
data = reader.read();
}catch (IOException e) {
e.printStackTrace();
}
while (data != -1) {
char charInput = (char) data;
try {
data = reader.read();
System.out.print(charInput); // this prints numbers
}catch (IOException e) {
e.printStackTrace();
}
}
reader.close();
}
}
DataInputStream.