File I/O in Java
Java I/O stream in flow in data you can either read or
you can write to.
It is used to perform read and write operations in file
permanently. Java uses streams to perform these tasks. Java I/O stream is also called File Handling, or File I/O. It is available in java.io package.
Stream
A stream is a sequence of data. In Java, a
stream is composed of bytes. It's called a stream because it is like a stream
of water that continues to flow.
In Java, 3 streams are created for us
automatically. All these streams are attached with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
the code to print output and an error message to the
console.
System.out.println(“siple message”);
System.err.println(“error message”);
the code to get input from console.
int i=System.in.read();
System.out.println(char)i);
OutputStream
vs InputStream
The explanation of OutputStream and
InputStream classes are given below:
OutputStream
Java application uses an output stream to
write data to a destination; it may be a file, an array, peripheral device or
socket.
InputStream
Java application uses an input stream to read
data from a source; it may be a file, an array, peripheral device or socket.
Let's understand the working of Java
OutputStream and InputStream by the figure given below.
java I/O file |
OutputStream class
OutputStream class is an abstract class. It
is the superclass of all classes representing an output stream of bytes. An
output stream accepts output bytes and sends them to some sink.
Useful methods of OutputStream
Method
|
Description
|
1)public void write(int)throw Exception
|
is used to write a byte to the current output stream.
|
2)public void write(byte[])throw exception
|
Is
used to write an array of byte to the current output stream.
|
3)public void flush()throw IO exception
|
flushes the current output stream.
|
4) public void close()throw IO Exception
|
Is
used to close the current output stream.
|
OutputStream Hierarchy
java file handling |
InputStream class
InputStream class is an abstract class. It is
the superclass of all classes representing an input stream of bytes.
Useful methods of InputStream
Method
|
Description
|
1)public void abstract int read()throw IO exception
|
Reads the next byte of data from the input stream.It returns-1 at the end of the file.
|
2)public void available()throw IO Exception
|
Returns
a estimate of the number of bytes that can be read from the current input
stream.
|
3)public void close()throw IO exception
|
Is used to closed
the current input stream.
|
InputStream Hierarchy
java IO file handling |
No comments:
Post a Comment