CSE307_Unit3_Java Input and Output
CSE307_Unit3_Java Input and Output
Java I/O
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the
classes required for input and output operations.
We can perform file handling in Java by Java I/O API.
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.
Let's see the code to print output and an error message to the console.
System.out.println("simple message");
System.err.println("error message");
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 Programming
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.
Method Description
InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an input stream
of bytes.
Method Description
1) public abstract int reads the next byte of data from the input stream. It
read()throws IOException returns -1 at the end of the file.
2) public int available()throws returns an estimate of the number of bytes that can
IOException be read from the current input stream.
InputStream Hierarchy
Java Programming
FileOutputStream Class
FileOutputStream is an output stream used for writing data to a file.
If you have to write primitive values into a file, use FileOutputStream class. You can write byte-
oriented as well as character-oriented data through FileOutputStream class. But, for character-
oriented data, it is preferred to use FileWriter than FileOutputStream.
Method Description
protected void finalize() It is used to clean up the connection with the file output
stream.
void write(byte[] ary) It is used to write ary.length bytes from the byte array to
the file output stream.
void write(byte[] ary, int It is used to write len bytes from the byte array starting at
off, int len) offset off to the file output stream.
void write(int b) It is used to write the specified byte to the file output
stream.
FileChannel getChannel() It is used to return the file channel object associated with the
file output stream.
FileDescriptor getFD() It is used to return the file descriptor associated with the
stream.
Example
import java.io.FileOutputStream;
public class FileOutputStreamExample
{
public static void main(String args[])
{
try
{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s = "Welcome to java files.";
byte b[] = s.getBytes();//converting string into byte array
fout.write(b);
Java Programming
fout.close();
System.out.println("success...");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
Success...
The content of a text file testout.txt is set with the data Welcome to javaTpoint.
testout.txt
Welcome to java files.
FileInputStream Class
FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data
(streams of raw bytes) such as image data, audio, video etc. You can also read character-stream
data. But, for reading streams of characters, it is recommended to use FileReader class.
public class FileInputStream extends InputStream
Method Description
int available() It is used to return the estimated number of bytes that can be
read from the input stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to b.length bytes of data from the input
stream.
int read(byte[] b, int It is used to read up to len bytes of data from the input stream.
off, int len)
long skip(long x) It is used to skip over and discards x bytes of data from the
input stream.
protected void It is used to ensure that the close method is call when there is
finalize() no more reference to the file input stream.
Example
import java.io.FileInputStream;
Java Programming
public class DataStreamExample
{
public static void main(String args[])
{
try
{
FileInputStream fin = new FileInputStream("D:\\testout.txt");
int i = 0;
while((I = fin.read()) != -1)
{
System.out.print((char)i);
}
fin.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream. Following is an example which makes use of these
two classes to copy an input file into an output file −
Example
import java.io.*;
public class CopyFile
{
public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;
try
{
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
}
finally
{
if (in != null)
{
in.close();
Java Programming
}
if (out != null)
{
out.close();
}
}
}
}
As a next step, compile the above program and execute it, which will result in creating an output.txt
file with the same content as we have in input.txt. So let's put the above code in CopyFile.java file
and do the following −
$javac CopyFile.java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit Unicode. Though there are
many classes related to character streams but the most frequently used classes
are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and FileWriter
uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time
and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an input
file (having Unicode characters) into an output file −
Example
import java.io.*;
public class CopyFile
{
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;
try
{
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
}
Java Programming
finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}
As a next step, compile the above program and execute it, which will result in creating an output.txt
file with the same content as we have in input.txt. So let's put the above code in CopyFile.java file
and do the following −
$javac CopyFile.java
$java CopyFile
File Class
The File class is an abstract representation of file and directory pathname. A pathname can be either
absolute or relative.
The File class have several methods for working with directories and files such as creating new
directories or files, deleting and renaming directories or files, listing the contents of a directory etc.
Constructor Description
File(File parent, String It creates a new File instance from a parent abstract pathname
child) and a child pathname string.
File(String pathname) It creates a new File instance by converting the given pathname
string into an abstract pathname.
File(String parent, It creates a new File instance from a parent pathname string
String child) and a child pathname string.
File(URI uri) It creates a new File instance by converting the given file: URI
into an abstract pathname.
Java Programming
Methods
Modifier Method Description
and Type
boolean canWrite() It tests whether the application can modify the file
denoted by this abstract pathname.String[]
boolean canExecute() It tests whether the application can execute the file
denoted by this abstract pathname.
boolean canRead() It tests whether the application can read the file
denoted by this abstract pathname.
Example
import java.io.*;
public class FileDemo
{
public static void main(String[] args)
{
try
{
File file = new File("javaFile123.txt");
if (file.createNewFile())
{
System.out.println("New File is created!");
}
Java Programming
else
{
System.out.println("File already exists.");
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Output:
RandomAccessFile
This class is used for reading and writing to random access file. A random access file behaves like
a large array of bytes. There is a cursor implied to the array called file pointer, by moving the cursor
we do the read write operations. If end-of-file is reached before the desired number of byte has
been read than EOFException is thrown. It is a type of IOException.
Constructor Description
Methods
void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or
write occurs.