Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Chapter 11 WEIGHTAGE

FILE HANDLING 6 MARKS

COMPUTER FILES
 Storage device of computer system can be broadly classified into two categories:
o Volatile storage and non-volatile storage
 Volatile storage is temporary.
o Value stored in variables is lost when a computer is shutdown.
o A java program that stores a value in a value in a variable name uses
Random Access Memory (RAM). Apart from variables, objects and their
reference are generally storedin RAM, once th program terminates or the
computer shuts down, the data is lost.
 Non-Volatile storage is a permanent storage.
o Data is not lost when a computer loses power
o A computer file is a collection of data stored on non-volatile device. Files
exist on permanent storage devices such as hard disks, USB drives,
optical disks and compactdiscs. Data stored in such files is often called
persistence data.
 Files can be classified broadly into two categories:
o Text Files and binary files
 Text files can be data files that contain facts, such as a payroll file that contains
employee numbers, names and salaries; or some text files can be program files or
application files thatstore software instructions.
o Text files contains data that can be read in a text editor because the
data has beenencoded using a scheme such as ASCII or Unicode.
o Files created through editors like gedit, vi, pico are example of text
files. They mayhave extensions like txt, java or c.
 Binary files contain data that has not been encoded as text. Their content are in
binaryformat, which means the data is accessed in terms of bytes.
o Some example of binary files are jpeg, mp3 and class.
 Java language supports various operations that can be performed on file or on
directories.
 Few operations that can be performed on files using java programs are listed below:
 Determining the path of a file or a directory opening a file
Writing in a file Reading from a file
Closing a file deleting a file
Querying the attribute of a file
 Java provides built-in classes that contain methods to help us with these tasks that is
related toFile. These classes are present in java.io package.
 Java uses the concepts of streams and it provides two different categories of java
classes to perform I/O operations on bytes and character

Presented by Nuzhat Ibrahim Memon 1


FILE CLASS IN JAVA
 The java.io.File class encapsulates information about the properties of a file or a directory.
 File class can be used to access attributes of files and directories.
 The creation of a file object that belongs to File class does not imply that the file or directory
exists.
 A file object encapsulates a pathname or reference to a physical file or a directory on the
hard disk.
 There are nearly 30 methods of File Class that can be used to perform various operations on a
file or directory.
 File class does not provide any method to read from a file or write into a file, there are several
stream classes to perform such operations.
 Constructors of File class
o By using the File class, we can create a reference to any file by providing its absolute path in
string format or by providing the relative path.
o The File class provides following constructors to refer a file or directory. [3 types are
available to create a java file object]
Constructor File class provide to refer to file or directory
The path as File fobj File(String Path) File fobj=new File fobj=new
File(“/directoryname/filename”); File(“/etc/passwd”);
Directory and File(String File fobj=new File fobj=new
filename as two directory_path, File(“/directoryname”, “filename”); File(“/etc”, “passwd”);
separate arguments String file_name);
Using reference to File(File directory, File dirobj=new File dirobj=new
directory String file_name); File(“/directorynam); File(“/etc”);
encapsulated in File fobj=new File fobj=new
dirobj object File(dirobj,”filename”); File(dirobj,”passwd”);

Method of File class


Method Description
boolean exists() Returns true if the file or directory exists, otherwise returns false
boolean isFile() Returns true if the file exists, otherwise returns false
boolean isDirectory() Returns true if the directory exists, otherwise returns false
boolean isHidden() Returns true if the file or directory is hidden
String getAbsolutePath() Returns the absolute path of the file or directory
String getName() Returns the name of the file or directory referred by the object.
String getPath() Returns the path of the file or directory
long length() Returns the number of bytes in that file
String[] list () Returns the name of files and directories in a directory
File[] listFiles() Returns an array of abstract pathnames denoting the files in the directory.
 To count the number of files and directories for a given directory, an array, listOfFiles of the File
class is used to store the file objects present in the directory.
 “The creation of a file object belongs to file class” does not imply that file or directory exists.
 Object is to be created in File class to refer to a particular directory.
 list() method can be use to list all the files present in the directory after creating an object of File class

INTRODUCTION TO STREAMS
 Java uses stream classes to carry out read and write operations on files.
 Hard disk can be classified as both input and output device as we can store and read data from the
Presented by Nuzhat Ibrahim Memon 2
files. There are various devices available in the market from different manufacturers and different
capabilities. For example, hard disk are manufactured by various companies and come with different
storage capacities like 500 GB or 1 Tb. Apart from this, hard disk can be connected using different
cables like USB or SATA.
 A java programmer does not need to worry about the technical details like type of hard disk
and its capacity while developing a program to perform read/write operations over the files.
This ispossible because java language provides functionality of streams.
 Stream is an abstract representation of an input or output device that is used as a source
or destination for data.
 We can visualize a stream as a sequence of bytes that flows into the program or that flows out of
our program.
 We can write data or read data using streams.
 When we write data to stream, the stream is called an output stream. The output stream
can transfer data from the program to a file on a hard disk or a monitor or to some other
computer over the network.
 An input stream is used to read data from an external device to the program; it can
transfer data from keyboard or from the file on a hard disk to the program.
 The main reason for using streams for input or output operations is to make our program
independent of the devices involved. Two advantages of streams are:
• Programmer does not need to worry about the technical details of the device.
• The program can work for a variety of input/output devices without any changes to the source code.

STREAM CLASSES IN JAVA


 Character is generally stored using ASCII or Unicode format
 Binary value of 53 is 00110101 and binary value of 5 is 00000101 and ASCII value of 5 is 53
 Binary value of the character is meaningful, when it is used for calculation.
 Java supports two types of streams: byte stream and character stream.
 Byte Stream::::Streams that transfer data in the form of bytes to the file or devices are
known as byte stream or binary stream.
o The files that are created using byte stream are known as binary files.
o Binary file should be used to store variables like integer, double or Boolean into a file
o Binary files can also be used to store array or object.
 Character Stream::::Text files and program codes are created using character stream. They
can be opened in text editors like vi or SciTE.
 Java provides two set of classes: character stream class and binary stream class.
 Character stream classes present in java.io package deal with the character/text data.
 Byte stream classes present in java.io package deal with binary data.
 Java streams can be classified into two basic types, namely input stream and output
stream.
 An input stream reads data from the source (file, keyboard) while the output stream writes data
to the destination (file, output device)
 The java.io. package contains a collection of stream classes that support reading and
writing in a file. To use these classes, a program needs to import the java.io. package.

Character Stream Classes


 Character stream classed are a group of classes available in java.io. package
 They can be used to read and write 16- bit Unicode character
Presented by Nuzhat Ibrahim Memon 3
Hierarchy of Character Stream class:


Stream

ByteStream Classes CharacterStream Classes

InputStream Classes OutputStream Classes Reader Classes Writer Classse

Character stream classes can be further classified into Reader and Writer classes

Reader Writer

InputStreamReader BufferedReader OutputStreamWriter BufferedWriter PrintWriter

FileReader Fiiewriter

Subclass of Reader Class InputStreamReaderand BufferReader


Subclass of InputStreamReader classFileReader
Superclass of FileWriterOutputStreamWriter

WRITER CLASSES
 Writer class is the base class for writing a character stream.
 The abstract Writer class defines the functionality that is available for all character output streams.
 FileWriter class is used in our program to perform write operations.
 Writer class is abstract so its used by its subclass.
 IOException
o Writer class throw IOException when there is a failed I/O operations
o IOEXception is a checked exception, so that we must take care of it. If we do not take care of
IOException it results into compiling error.
 The OutputStreamWriter class extends Writer Class. It converts stream of characters to a stream of
bytes.
 The FileWriter class extends OutputStreamWriter and outputs characters to a file.
 FileWriter(String filepath, Boolean append) throws IOException. In this constructor by true value of
append, characters are appended to the end of file and by false value of append, the exiting
contents of the file are overwritten.
 Methods like write() and close() from Writer class
 Statement to create a file charfile1.txt by using file object named fwobject:
o FileWriter fwobject=new FileWriter(“charfile1.txt”);
 write() mehtod is used to write few lines into the file.
 fwobject.close() is used to close object named fwobject.
 cat charfile1 is used to display contents of a file charfile1.txt
 To close stream object is an important process after writing to a file accomplished.

Presented by Nuzhat Ibrahim Memon 4


 It is important to close steam object after writing to a file accomplished because
o open files consume system resources and o depending on the file mode, other programs may
not be able to access them.
READER CLASSES
 Reader class is the base class for reading a character stream.
 The abstract Reader class defines the functionality that is available for all character input
stream.
 File Reader class is used in our program to perform read operations. FileReader class is used to
reads characters from a file.
 Methods of FileReader Class
Method Description
void close() Closes the stream
Int read() Reads next available character from the stream, it returns “-1” to indicate the end of stream.
 InputStreamReader class extends Reader class.
 InputStreamReader class converts a stream of bytes to a stream of characters.
 Constructor of FileReader class
o FileReader(String filepath) throws FileNotFoundException
o FileReader(File fileobj) throws FileNotFoundException
o FileReader frobject=new FileReader(“/java/files/charfile1.txt”);
 read() method of FileReader class is used to reads data from the file.
 read() method is inherited from Reader() class
 Special symbol is there to show end of java file.
 read() method used -1 to show end of data in stream
 EOF  End of file

BYTESTREAM CLASSES
 Java provides set of binary streams and their associated classes for numeric calculations.
 The FileInputStream and FileOutputStream classes in the java.io package give us the ability to read
and write bytes from and into any files in the disk.

FileInputStream class
 FileInputStream class is a subclass of the InputStream class.
 Methods of FileInputStream class
Methods Description
void close() Closes the file input steam and releases any system resources associated with the stream.
int read() Reads a byte of data from this input stream.
Int read(byte[] b) Reads up to b.length bytes of data from this input stream into an array of bytes.
 Type casting is to be applied to convert integer to character (converting a data type into another data type)

FileOutputStream class
 It is subclass of OutputStream.
 It is used to write bytes to the file or some output stream.
 To use this class and its method, first we need to create a file object, then we could use the write
method derived from the abstract class OutputStream to write byte into a file.
 write() method derived from OutputStream is used to write byte into a file.


5
Presented by Nuzhat Ibrahim Memon
Methods of FileOutputStream class
Methods Description
void close() Closes the file output steam & releases any system resources associated with the stream.
int write() Writes the specified byte to this file output stream.
Int write(byte[] b) Writes b.length bytes of data from the specified byte array to this file output stream.
 A constructor of a FileOutputStream class can be accepted as a
o A String containing the path to the file location o Object of the File class
 Constructor of FileOutputStream class
o FileOutputStream(String name) throws FileNotFoundException
o FileOutputStream(File file) throws FileNotFoundException
o File fobj=new File(“/java/files/charfile1.txt”);
FileOutputStream fosobj=new FileOutputStream(fobj); OR
FileOutputStream fosobj=new FileOutputStream((“/java/files/charfile1.txt”);
 Constructor can throw FileNotFoundException
o If the filename refers to directory ratherthan regular file
o File does not exist
o File cannot be opened for some reason

PROCESSING INPUT FROM KEYBOARD


 A program can get input of data from live interaction through keyboard/GUI or it may take input
as command line arguments or from files. [live interactionkeyboard/GUI, CommandCLA)
 Although there are many classes that facilitate the input from keyboard.
 Scanner class of java.util package and console class of java.io package facilitate the input
from keyboard or from the file.

SC ANNER CLASS [java.util]


 Scanner class provides methods to read input from the keyboard or from the file. 
 A special feature of this class is that it breaks the input string into tokens (words) using a delimiter. 
 White space is generally used symbol in Scanner class. Different kind of each token is used in
Scanner class.“Byteland-2019” is read as String-int
 Constructor of scanner class
Syntax Object
Scanner(String str) String
Scanner(InputStream inp) InputStream object
Scanner(File fobj) throws FileNotFoundException File object
 Constructor is used to read form the keyboard by Scanner object
Scanner kbinp=new Scanner(System.in);
 Constructor of Scanner class accept as an argument to rad form keyboard(Standard input)
System. in
 Methods of Scanner class
Methods Description
void close() Closes the scanner
String next() Returns the next token
boolean hasNext() Returns true if there is a token in input
int nextInt() Scans the next token of the input as Int
float nextFloat() Scans the next token of the input as Float
String nextLine() Scans the next token of the input as Line

Presented by Nuzhat Ibrahim Memon 6


Console Class [javo.io]
 We use Console class especially when the input is to be typed in hidden form (character must
not be echoed on screen).
 The console class provides a method for reading password.
 Array of character will be return type while reading the password.
 Methods of Console Class
Methods Description
String readLine() This method reads a single line of text from the console.
Char [] readPassword() This method reads a password or passphrase from the console with
echoing disabled.
Console printf(String format, This method is used to write a formatted string to this console’s
Object args) output stream using the specified format string and arguments.

Extra Points
 File refers to a collection of data stored on anonvolatile device in a
 computer system.
 Smallest to largest piece of data in the datahierarchy is character:field:record:file
 More about Stream:
o Streams always flow in two directions, streamsare channels through which the data flow andonly one
stream can be open in a program at a time.
 Space is used as a separator between fields of arecord.
 Scanner class can be used for performingfollowing operation:
o Accept input from the keyboard
o Read from the file
o Parse s string separated by delimiters
 Two categories of storage device::Volatilestorage temporary & Non-volatile
storagePermanent
 Two categories of file: Text(character)files &Binary files
 30 methods are available in java for a file class and Many classes are there in java to work on
character and byte.
 Abstract classes cannot be used to create anobject.
 Java.io.Writer and java.io.Reader is known as abstract class and come with the set of methodsto be
implemented by its subclasses. Both created from an object-class.
 http://docs.oracle.com/javacse/6/docs/api/ website contain detailed description of methodsand
constructors
 FileReader and Scanner both classes are used toread from the file or from the keyboard.
 Java file provide classes to store object, to retrieve objects and to access a file randomly.
 Java provides classes to perform operations insequentially or to directly jump to nth record.
 Reader is used to access data from a file
 Scanner Classjava.util
 Console Class [hidden password]java.io

You might also like