Chapter 4
Chapter 4
Faculty Of Informatics
Department Of Computer Science
But also, objects from two or more classes need to be combined for solving specific tasks.
Java is a modern language that has been developed when the World Wide Web was becoming a reality.
As such, the data can be written/read to/from many sources, including the
Console/keyboard,
The network.
The presence of the Web stimulated the creation of classes for handling various encodings of the
information (English and European languages but also Arabic and Asian languages; and also binary data).
Definitions
In Java input and output is defined in terms of an abstract concept called stream. A Stream is a sequence
of data. If it is an input stream it has a source. If it is an output stream it has a destination.
The java.io package provides a large number of classes to perform stream IO.
There are two major kinds of streams: character streams and byte streams.
In java, characters are encoded with 16 bit unicodes —
Examples of binary data include image and audio files, jpeg and mp3 files Information can be read from an external
source or written to an external source.
Overview
Several classes are found in the I/O package reflecting the fact that I/O involves two different kinds of
streams and three different modes of access.
Stream:
character, byte;
Access:
The I/O package contains some 50 classes, 10 interfaces and 15+ Exceptions.
On the top of this, generally objects from 2 or 3 classes need to be combined to carry out a basic task.
Example.
For most applications, I/O with character stream is no more complicated than I/O with binary streams. Input and
output done with stream classes automatically translates to and from the local character set.
A program that uses character stream in place of byte streams automatically adapts to the local character set and is
ready for internationalisation - all without extra effort by the programmer.
All character stream classes are descended from Reader and Writer. As with byte streams, there are character
stream classes that specialise in file I/O: FileReader and FileWriter.
Classes under this hierarchy are used for reading and writing characters from file, which are text files.
FileReader: import java.io.FileReader;
class IOTest{
public void readFile(){
FileReader class is used for reading try {
streams of characters from a file. //creating FileReader object.
FileReader fr =
Commonly used constructors of new FileReader("F:\\New folder\\data1.txt");
FileReader: int i;
//read file.
1. FileReader(File file) while((i=fr.read())!=-1){
System.out.print((char)i);
Creates a new FileReader, given }
the File to read from. } catch (Exception e) {
e.printStackTrace();
2. FileReader(String fileName) }
}
Createsa new FileReader, given }
public class FileReaderExample {
the name of the file to read public static void main(String args[]){
from. //creating IOTest object.
IOTest obj = new IOTest();
//method call.
obj.readFile();
}
}
FileWriter: class IOTest{
String str = "Hello Students";
public void writeFile(){
FileWriter class is used for streams try {
//Creating FileWriter object.
of characters to a file. //It will create a new file before writing if not exist.
FileWriter fw = new FileWriter("F:\\New older\\
Commonly used constructors of data6.txt");
fw.write(str);
FileWriter: fw.flush();
//Close file after write operation.
1. FileWriter(File file) fw.close();
System.out.println("Contents written successfully.");
Creates a FileWriter object } catch (Exception e) {
e.printStackTrace();
given a File object. }
}
2.FileWriter(String fileName) }
public class FileWriterExample {
Creates a FileWriter object public static void main(String args[]){
//Creating IOTest object.
given a file name. IOTest obj = new IOTest();
//method call
obj.writeFile();
}
}
Byte Streams
• Programs use byte streams to perform input and output of 8-bytes. All byte stream classes are descended from
InputStream and OutputStream classes.
• There are many byte stream classes. To demonstrate how byte streams work, we'll focus on the file I/O byte streams,
File Input Stream and File Output Stream. Other kind of byte streams are used much in the same way; the difference is
mainly in the way they are constructed.
• These classes are used for binary data. We can use these classes for text files as well.
• Character streams are packaging for binary streams. This means that the character stream uses the binary stream
internally.
• Java uses OutputStream and InputStream for Writing data to destination and Reading data from source, respectively.
• OutputStream and InputStream are abstract classes. So we can't use them directly
• Output Stream class: OutputStream class is an abstract class. It is the superclass of all classes representing an output stream of
bytes. Like FileOutputStream, ObjectOutputStream, etc.
• Input Stream class: InputStream class is an abstract class. It is the superclass of all classes representing an input stream of bytes,
like File Input Stream, Object Input Stream, etc.
The package java.io contains the classes that provide the foundation for
java’s support for stream I/O
Reading Data From an InputStream
The abstract superclass InputStream declares an abstract method read() to read one data-byte from the input
source.
The read () method returns an int instead of a byte, because it uses -1 to indicate end-of- stream.
The read () method blocks until a byte is available, an I/O error occurs, or the "end-of- stream" is detected. The
term "block" means that the method (and the program) will be suspended. The program will resume only when
the method returns.
Writing to an Output Stream
Similar to the InputStream, the abstract superclass OutputStream declares an abstract method write() to write a
data-byte to the output sink.
The least-significant byte of the int argument is written out; the upper three bytes are discarded.
It throws an IOException if an I/O error occurs (for example, if output stream has been closed).
InputStream and OutputStream are abstract classes that cannot be instantiated. You need to choose an appropriate
concrete subclass to establish a connection to a physical device.
For example, you can instantiate a FileInputStream or FileOutputStream to establish a stream to a physical
disk file.
class IOTest{
FileInputStream stream is used for reading public void readFile(){
try {
data from the files. //creating FileInputStream object.
FileInputStream fis =
Commonly used constructors of new FileInputStream("F:\\New folder\\data1.txt");
int i;
FileInputStream: //read file.
while((i=fis.read())!=-1){
System.out.print((char)i);
1. FileInputStream(File file)
}
} catch (Exception e) {
Creates a FileInputStream by opening a e.printStackTrace();
connection to an actual file, the file named }
}
by the File object file in the file system. }
public class FileInputStreamExample {
2. FileInputStream(String name) public static void main(String args[]){
//creating IOTest object.
Creates a FileInputStream by opening a IOTest obj = new IOTest();
//method call.
connection to an actual file, the file named
obj.readFile();
by the path name name in the file system. }
}
import java.io.FileOutputStream;
Programs use byte streams to perform input and output of 8-bit bytes.
All byte stream classes are descended from InputStream and OutputStream.
Byte streams should only be used for the most primitive I/O. It represents a kind of
low-level I/O so you should avoid in case complicated data types like text or
graphics.
ByteArrayInputStream:
import java.io.ByteArrayInputStream;
A ByteArrayInputStream class provides an internal buffer for the class IOTest{
String str = “Hello Student";
bytes read from input stream. public void readFile(){
try {
Commonly used constructors of ByteArrayInputStream: //Converting string into byte array.
byte b[] = str.getBytes();
//Creating ByteArrayInputStream object.
1. ByteArrayInputStream(byte[] buf)
ByteArrayInputStream bais =
new ByteArrayInputStream(b);
Creates a ByteArrayInputStream so that it uses buf as its int i;
buffer array. //read file.
while((i=bais.read())!=-1){
System.out.print((char)i);
2. ByteArrayInputStream(byte[] buf, int offset, int length) }
} catch (Exception e) {
Creates ByteArrayInputStream that uses buf as its buffer e.printStackTrace();
}
array. }
}
Commonly used methods of ByteArrayInputStream: public class ByteArrayInputStreamExample {
public static void main(String args[]){
1. public int read() This method reads the next byte of data //creating IOTest object.
IOTest obj = new IOTest();
from the InputStream. Returns an int as the next byte of data. //method call.
obj.readFile();
If it is end of file then it returns -1.
}
}
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
When the BufferedInputStream is created, an internal buffer array is created. As bytes from the stream are
read or skipped, the internal buffer is refilled as necessary from the contained input stream, many bytes at a
time.
The mark operation remembers a point in the input stream and the reset operation causes all the bytes read
since the most recent mark operation to be reread before new bytes are taken from the contained input
stream.
class IOTest{
public void readFile(){
Commonly used constructors of try {
BufferedInputStream: //creating FileInputStream object.
FileInputStream fis =
1. BufferedInputStream(InputStream in) new FileInputStream("F:\\New folder\\data1.txt");
//Creating BufferedInputStream object.
Creates a BufferedInputStream and saves BufferedInputStream bis =
new BufferedInputStream(fis);
its argument, the input stream in, for later int i;
use. //read file.
while((i=bis.read())!=-1){
2. BufferedInputStream(InputStream in, System.out.print((char)i);
}
int size) } catch (Exception e) {
Creates e.printStackTrace();
a BufferedInputStream with the }
specified buffer size, and saves its }
argument, the input stream in, for later }
public class BufferedInputStreamExample {
use. public static void main(String args[]){
//creating IOTest object.
IOTest obj = new IOTest();
//method call.
obj.readFile();
}
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
BufferedOutputStream class IOTest{
String str = "Hello Student";
public void writeFile(){
try {
Commonly used constructors of //Creating FileOutputStream object.
BufferedOutputStream: //It will create a new file
//before writing if not exist.
1.BufferedOutputStream(OutputStream FileOutputStream fos =
new FileOutputStream("F:\\New folder\\data3.txt");
out) //Creating BufferedOutputStream object.
Creates BufferedOutputStream bos = new
a new buffered output stream BufferedOutputStream(fos);
to write data to the specified underlying byte b[]=str.getBytes();
output stream. bos.write(b);
bos.flush();
2.BufferedOutputStream(OutputStream bos.close();
System.out.println("Contents written successfully.");
out, int size) } catch (Exception e) {
e.printStackTrace();
Creates a new buffered output stream }}
to write data to the specified underlying }
public class BufferedOutputStreamExample {
output stream with the specified buffer public static void main(String args[]){
size //Creating IOTest object.
IOTest obj = new IOTest();
//method call
obj.writeFile();
}
What is File Handling in Java?
File handling in Java implies reading from and writing data to a file.
The File class from the java.io package, allows us to work with different
formats of files.
In order to use the File class, you need to create an object of the class and
specify the filename or directory name.
For example:
Java File Methods
Below table depicts the various methods that are used for performing
operations on Java files.
import java.io.IOException;
In this case, to create a file you can use public class CreateFile {
public static void main(String[] args) {
the createNewFile() method. This method try {
//Creating an object of a file
returns true if the file was successfully created, File myObj = new
File("D:FileHandlingNewFilef1.txt");
and false if the file already exists. if (myObj.createNewFile()) {
System.out.println("File created: " +
Let’s see an example of how to create a file in myObj.getName());
} else {
Java. System.out.println("File already exists.");
}
In the above code, a file named NewFilef1 gets } catch (IOException e) {
System.out.println("An error occurred.");
created in the specified location. If there is an e.printStackTrace();
}
error, then it gets handled in the catch block. }
2. Get File information import java.io.File; // Import the File class