Lesson 4 | Data streams |
Objective | Data streams use Java-defined data types |
Data Input Streams
DataInputStream
Program that uses FileInputStream and InputStreamReader to read in a File
The following program will read in the text file and at location c:\\input.txt and write it out to the console.
- Declare an object of type FileInputStream "inputStream" that contains the location of the input file.
- Chain that object with InputStreamReader
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();
}
}
Read Using Buffered Reader - Exercise
Here is the second part of the exercise concerning reading from the standard input.
This exercise asks you to modify the program you wrote in the previous exercise to read from
DataInputStream
.
Read Using Buffered Reader - Exercise
Java DataStreams - Quiz