How Do I Read Stream Java?
Java uses the stream interface for reading and writing from the console, from files, and even for communicating over the Internet with other applications.
Instructions
-
-
1
Create a new, blank text file to hold the Java class. You can use any text editor you prefer, including Windows Notepad. Dedicated Java editors like Netbeans or Eclipse will include extra features. Name the text file "StreamTutorial.java."
-
2
Paste the following code into the text file to define the basic Java class:
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
public class StreamTutorial {
public static void main(String[] args) {
}
}
All code for this tutorial will go within the "public static void main" section.
-
-
3
Paste the following code:
try {
InputStream in = System.in;
while (true) {
int x = in.read();
System.out.print((char) x);
if (((char)x) == '-') break;
}
} catch (IOException e) {
e.printStackTrace();
}
This code creates an InputStream from the console, reads each byte from the console, one by one, and echos it back to the user. If a '-' is typed, the program stops. This code is the absolute minimum to read from a stream. However, it is a bit laborious. There are helper classes to make the input process easier.
-
4
Replace the code from step 3 with this code:
InputStream in = System.in;
Scanner sin = new Scanner(in);
String s = sin.nextLine();
System.out.println(s);
int i = sin.nextInt();
System.out.println(i);
boolean b = sin.nextBoolean();
System.out.println(b);
This code uses the helper class Scanner, which can interpret data from an InputStream in terms of each of the major primitive data types.
-
1
Tips & Warnings
Java streams are not limited to reading from the console. Classes exist for reading from files and the Internet with the same interface.