In this tutorial, I am going to explain about file IO in java. How can we deal with file handling, how can we upload a file, what are stream API in java and much more. Let us get started.
Java.io package
provides a wide range of classes that we can use to perform file input output
operations (file IO). These classes are known as streams. The stream classes
support almost all data types.
What is stream
In normal terms,
a stream is a sequence of something; similarly in java stream is the sequence
of data. Mainly the stream can be:
1.
InputStream – used in reading source data.
2. OutputStream – used in writing data to output.
The flow of
stream goes like:
First, let’s get
familiar with file IO streams in java by taking easy yet important examples.
We will discuss
three examples byte streams, character stream and standard stream. After these
examples, we will move forward to reading from and writing to the file using IO
in java.
Byte Stream
To perform input and output on 8-bit bytes we use byte stream. Below example make use of FileInputStream and FileOutputStream to copy the content of one file into another.
Now, create a
file with name input.txt and write
some content in it.
Compiling and
running the above code will result in creating a file with name output.txt and copying the content into
output.txt from input.txt.
Character Stream
Unlike byte
stream, the character stream is used to perform IO operations for 16-bit
Unicode. The below example uses FileReader
and FileWriter to perform IO
operations. Both FileReader and FileWriter use FileInputStream and FileOutputStream
internally, but the difference is that FileReader reads two bytes at a time and
FileWriter writes two bytes at a time.
Now, create a file with name input.txt and write some content in it.
Compiling and
running the above code will result in creating a file with name output.txt and copying the content into
output.txt from input.txt.
Standard Stream
These streams
are used when we want to get the input from the user using the command line and
print that into a file or save that into the file. Similar to C and C++, java
provides three standard stream classes:
1. Standard
Input – this stream is
represented as System.in. This is
usually used when we want to insert the data into the program using the command
line or user input data.
2. Standard
Output – this stream is
represented as System.out. This is
usually used to display the user input data on the screen or in the console.
3. Standard
Error – this stream is
represented as System.err. this is
usually used to display any error message caused because of programmer data.
Below program makes use of InputStreamReader to read the user entered data until the user types “x”.
By Compiling and
running the code we can see that the console will accept the characters from
the user and will keep of reading the characters until ‘x’ is pressed.
Reading and writing files
InputStream and OutputStream
are the main classes. The hierarchy goes like this.
Out of these
classes, in this tutorial, we will discuss only the important ones.
FileInputStream
This stream
class is used to read the content from the file. To use this stream make sure
that the file specified should exist is the drive specified.
We can use FileInputStream constructor to create
the object
InputStream input = new
FileInputStream(“C:/java/hello”);
This constructor
takes file location to create an InputStream object and reads the file.
There are many
internal methods which we can use to perform the stream operation. They are as
follows.
1. public
void close() throws IOException – Closes file output stream should be used in finally block.
2. public
int read(int r) throws IOException – reads specified data returns an int. Returns -1 when
file ends.
3. protected
void finalize() throws IOException – used in clean up like cleaning up the connection to
the file.
4. public
int read(byte[] r) throws IOException – it reads from the InputStream upto r.read(). Return -1
when end of file.
5. public
int available() throws IOException – gives the number of bytes available to read.
ByteArrayInputStream
This class
creates a buffer in the memory to be used as an InputStream. The byte array is
the input source. The below example uses ByteArrayInputStream
and ByteArrayOutputStream.
Output:
Print the
content
b y t e a r r a
y
Converting the
characters to upper case
B
Y
T
E
A
R
R
A
Y
DataInputStream
This stream
class is used to read primitives data type. DataInputStream offers multiple
methods which are given below:
1. public
final int read(byte[] r, int off, int length) throws IOException – read the data up to the length of the byte array
specified. Returns the total number of bytes or -1 if the file comes to end.
2. public
final int read(byte[] b) throws IOException – reads byte[] specified and return the total number
of bytes read or -1 when the file comes to end.
3. public
final Boolean readBoolean() throws IOException
4. public
final byte readByte() throws IOException
5. public
final short readshort() throws IOException
6. public
final int readInt() throws IOException
7. public
String readLine() throws IOException
Below example reads data and convert it into capital letter and copies into another file.
FileOutputStream
FileOutputStream
is used to create the file and write into it. If the file is not already
available FileOutputStream will create the file. Constructor is as follow:
OutputStream out = new
FileOutputStream(“C:/javaTutorial/FileOutputExample”);
Following are
the methods and their descriptions
1. public
void close() throws IOException – use to close FileOutputStream object.
2. protected
void finalize() throws IOException – the method used for clean up operations.
3. public
void write(int b) throws IOException – writes a specified byte to the output stream.
4. public void write(byte[] b) throws IOException – Writes the mentioned byte array.
Directories in java
Using IO
operations provided by java we can create directories and make changes to it.
Creating Directories
mkdir() and mkdirs() are the two File
utility methods which we can use to create directories.
mkdir() will create the directory, if created, will return true otherwise on
failure it will return false. Failure will occur when there is some problem for
the path.
mkdirs() will create the directory including all the parent directories.
Example
Listing Directory
Below is the
example of how we can use list() method
provided by File object.
Output
List of all the directories and files available in /temp directory.
I hope I have
covered all the points related to File handling or File IO in java. Please feel
free to add comments and share knowledge.
0 Comments