In: Computer Science
How to write IO program in java?
Java brings different Streams with its I/O package that helps the user to perform all the input-output operations.
These streams support all the types of objects, data-types, characters, files etc to fully execute the I/O operations.
Before exploring various input and output streams lets look at 3 standard or default streams that Java has to provide which are also most common in use:
Here is a list of the various print functions that we use to output statements:
print(): This method in Java is used to display a text on the console.
println(): This method in Java is also used to display a text on the console. It prints the text on the console and the cursor moves to the start of the next line at the console.
3.System.err: This is the standard error stream that is used to output all the error data that a program might throw, on a computer screen or any standard output device.
code:
import java.io.IOException; import java.io.InputStreamReader; public class fileStreamTest { public static void main(String args[]) throws IOException { InputStreamReader inp = null; inp = new InputStreamReader(System.in); System.out.println("Enter characters according your choice " + " and Enter '0' to quit."); char c; do { c = (char)inp.read(); System.out.println(c); } while (c != '0'); } }
output:
Enter characters according your choice and Enter '0' to
quit.
my name is Bob
m
y
n
a
m
e
i
s
B
o
b
0
0
Process finished with exit code 0
streams can be divided into two primary classes:
1) Input Stream: These streams are used to read
data that must be taken as an input from a file or any peripheral
device.
For eg., FileInputStream, BufferedInputStream etc.
2) Output Stream: These streams are used to write data as outputs into an array or file or any output peripheral device.
For eg., FileOutputStream , ByteArrayOutputStream etc.
code
import java.io.FileReader; import java.io.IOException; public class fileStreamTest { public static void main(String args[]) throws IOException { FileReader sourceStream = null; try { sourceStream = new FileReader("test.txt"); //read test.text file int temp; while ((temp = sourceStream.read())!= -1) System.out.println((char)temp); } finally { if (sourceStream != null) sourceStream.close(); } } }
output:
M
y
n
a
m
e
i
s
A
l
i
c
e
code(SS):
output(SS):
we can various program using IO.