0% found this document useful (0 votes)
7 views30 pages

Chapter 4

Chapter Four of the Advanced Java Programming course focuses on Input/Output (I/O) streams and file management in Java. It explains the concepts of character and byte streams, their classes, and how to read from and write to files using various stream classes. The chapter also includes code examples demonstrating the use of FileReader, FileWriter, FileInputStream, and FileOutputStream for handling file operations.

Uploaded by

bekema
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views30 pages

Chapter 4

Chapter Four of the Advanced Java Programming course focuses on Input/Output (I/O) streams and file management in Java. It explains the concepts of character and byte streams, their classes, and how to read from and write to files using various stream classes. The chapter also includes code examples demonstrating the use of FileReader, FileWriter, FileInputStream, and FileOutputStream for handling file operations.

Uploaded by

bekema
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Kibur College

Faculty Of Informatics
Department Of Computer Science

Advanced Java Programming: Chapter Four


IO Stream and File Management 1
Java Programming BY. Bekema Gidissa
Contents

 Chapter 4: Streams and File I/O (4hr)

 4.1. Input output streams

 4.1.1. Various stream classes

 4.1.2. Using Streams

 4.1.3. Object Streams

 4.2. File management


Java I/Os
 Java I/Os seem a bit complex at first.

 There are many classes.

 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,

 External devices (such as hard disks) or

 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.

 A stream is an ordered sequence of data that has a source or a destination.

 There are two major kinds of streams: character streams and byte streams.
 In java, characters are encoded with 16 bit unicodes —

 Character streams are associated with text-based (human readable) i/os.

 The character streams are called readers and writers.

 This Byte streams are associated with data-based (binary) I/os.

 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:

 read, write, direct.

 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.

InputStreamReader in = new InputStreamReader( new FileInputStream( "data" ) );


import java.io.File;
import java.util.Date;
 In java, I/O is used to receive input
public class FileInfoExample {
data and produce output by processing
public static void main(String[] args) {
the input provided. File apath = new File("C:/test/abc.txt");
// Check if exists.
System.out.println("Path exists? "+ apath.exists());
if (apath.exists()) {
// Check if 'apath' is a directory.
System.out.println("Directory? "+ apath.isDirectory());
// Check 'apath' is a Hidden path.
System.out.println("Hidden? "+ apath.isHidden());
System.out.println("Simple Name: " + apath.getName());
System.out.println("Absolute Path: "+ apath.getAbsolutePath());
// Check file size (in bytes):
System.out.println("Length (bytes): " + apath.length());
// Last modify (in milli second)
long lastMofifyInMillis = apath.lastModified();
Date lastModifyDate = new Date(lastMofifyInMillis);
System.out.println("Last modify date: " + lastModifyDate);
}
}
Character Streams
 The Java platform stores character values using Unicode conventions. Character I/O stream automatically
translates this internal format to and from the local character set. In Western locales, the local character set is
usually an 8-bit superset of ASCII.

 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 the input byte read as an int in the range of 0 to 255, or

 Returns -1 if "end of stream" condition is detected, or

 Throws an IOException if it encounters an I/O error

 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.

 write() : Takes an int as the input parameter

 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.

 We can use FileInputStream and FileOutputStream for File related operations


FileInputStream:
import java.io.FileInputStream;

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;

FileOutputStream: class IOTest{


String str = "Hello Student";
public void writeFile(){
try {
 FileOutputStream is used to create a file //Creating FileOutputStream object.
//It will create a new file before writing if not
and write data into it. It will create a exist.
file, if it does not exist. FileOutputStream fos =
new FileOutputStream("F:\\New folder\\data2.txt");
 Commonly used constructors of byte b[]=str.getBytes();
fos.write(b);
FileOutputStream: fos.flush();
 1. FileOutputStream(File file) //Close file after write operation.
fos.close();
 Creates a file output stream to write to System.out.println("Contents written successfully.");
the file represented by the } catch (Exception e) {
e.printStackTrace();
specified File object.
}
 2. FileOutputStream(String name) }
}
 Creates a file output stream to write to public class FileOutPutStreamExample {
the file with the specified name. public static void main(String args[]){
//Creating IOTest object.
IOTest obj = new IOTest();
//method call
obj.writeFile();
} }
import java.io.FileInputStream;
import java.io.FileOutputStream;

 Example: Reading the data class IOTest{


public void readFile(){
from one file and writing it try {
//Creating FileInputStream object.
into another file. FileInputStream fis =
new FileInputStream("F:\\New folder\\data1.txt");
//Creating FileOutputStream object.
FileOutputStream fos =
new FileOutputStream("F:\\New folder\\data7.txt");
int i;
//read file.
while((i=fis.read())!=-1){
fos.write(i);
}
System.out.println("Content written successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ReadWriteExample {
public static void main(String args[]){
//creating IOTest object.
IOTest obj = new IOTest();
//method call.
obj.readFile();
}
}
Byte Streams in java:

 Programs use byte streams to perform input and output of 8-bit bytes.

 All byte stream classes are descended from InputStream and OutputStream.

 Always close the files to avoid serious resource leaks.

 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;

ByteArrayOutputStream: class IOTest{


String str = "Hello Student";
public void writeFile(){
 try {
ByteArrayOutputStream class uses byte array to write
data. The buffer automatically grows as data is written FileOutputStream fos = new FileOutputStream("F:\\New
to it. folder\\data5.txt");
//Creating ByteArrayOutputStream object.
 Commonly used to constructors of ByteArrayOutputStream baos=new ByteArrayOutputStream();
ByteArrayOutputStream: baos.write(str.getBytes());
baos.writeTo(fos);
 1. ByteArrayOutputStream () baos.flush();
//Close file after write operation.
 Creates a new byte array output stream. baos.close();
System.out.println("Contents written successfully.");
 2. ByteArrayOutputStream (int size) } catch (Exception e) {
e.printStackTrace();
 Creates a new byte array output stream, with a }
buffer capacity of the specified size, in bytes. }
}
 Commonly used methods of ByteArrayOutputStream: public class ByteArrayOutputStreamExample {
public static void main(String args[]){
 1. public void writeTo(OutputStream outSt) Writes //Creating IOTest object.
the entire content of this Stream to the specified stream IOTest obj = new IOTest();
argument. //method call
obj.writeFile();
}
}
BufferedInputStream and BufferedOutputStream
 A BufferedInputStream adds functionality to another input stream, namely, the ability to buffer the input
and to support the mark and reset methods.

 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.

 The BufferedOutput Stream implements a BufferedOutputStream. By setting up such an output stream, an


application can write bytes to the underlying output stream without necessarily causing a call to the
underlying system for each byte written.
BufferedInputStream import java.io.BufferedInputStream;
import java.io.FileInputStream;

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.

Method Type Description


canRead() Boolean It tests whether the file is readable or not
canWrite() Boolean It tests whether the file is writable or not
createNewFile() Boolean This method creates an empty file
delete() Boolean Deletes a file
exists() Boolean It tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath() String Returns the absolute pathname of the file
length() Long Returns the size of the file in bytes

list() String[] Returns an array of the files in the directory


mkdir() Boolean Creates a directory
File Operations in Java
 Basically, you can perform four operations on a file. They are as follows:
 Create a File
 Get File Information
 Write To a File
 Read from a File
 Now, let’s get into the details of each of these operations
1. Create a File import java.io.File;

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

public class FileInformation {


public static void main(String[] args) {
 Let’s see how to get file // Creating an object of a file
File myObj = new File("NewFilef1.txt");
information using various if (myObj.exists()) {
methods with the help of below // Returning the file name
System.out.println("File name: " + myObj.getName());
example code // Returning the path of the file
System.out.println("Absolute path: " +
myObj.getAbsolutePath());
// Displaying whether the file is writable
System.out.println("Writeable: " + myObj.canWrite());
// Displaying whether the file is readable or not
System.out.println("Readable " + myObj.canRead());
// Returning the length of the file in bytes
System.out.println("File size in bytes " + myObj.length());
} else {
System.out.println("The file does not exist.");
}
}
}
Write to a File
import java.io.FileWriter;
import java.io.IOException;

 3. In the following example, public class WriteToFile {


public static void main(String[] args) {
I have used try {
FileWriter myWriter = new
the FileWriter class FileWriter("D:FileHandlingNewFilef1.txt");
// Writes this content into the specified file
myWriter.write(Java is the prominent programming
together with language of the millenium!");

its write() method to write //Closing is necessary to retrieve the resources


allocated
some text into the file. Let’s myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
understand this with the System.out.println("An error occurred.");
e.printStackTrace();
help of a code. }
}
}
import java.io.File;
import java.io.FileNotFoundException;
4. Read from a File //Import the Scanner class to read text files
import java.util.Scanner;

public class ReadFromFile {


 In the following example, I have used the Scanner public static void main(String[] args) {
class to read the contents of the text file. try {
//Creating an object of the file for reading th
data
File myObj = new
File("D:FileHandlingNewFilef1.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

You might also like