Computer Class 12 GSEB Solutions Chapter 11 File Handling

Students frequently turn to Computer Class 12 GSEB Solutions and GSEB Computer Textbook Solutions Class 12 Chapter 11 File Handling for practice and self-assessment.

GSEB Computer Textbook Solutions Class 12 Chapter 11 File Handling

Question 1.
Why is a file important in java programming ? Under what circumstances will you store the data in files ?
Answer:
Files can be further classified broadly into two categories :
(1) Text files and
(2) Binary files.

(1) Text files :

  • Text files contain data that can be read in a text editor because the data has been encoded using a scheme such as ASCII or Unicode.
  • Text files can be data files that contain facts, such as payroll file that contains employee numbers, names and salaries; or some text files can be program files or application files that store software instructions.
  • Files created through editors like gedit, vi, pico are examples of text files. They may have An extensions like txt, java or c.

(2) Binary files :

  • Binary files contain data that has not been encoded as text.
  • Their contents are in binary format, which means the data is accessed in terms of bytes.
  • Some examples extensions of binary files jpeg, mp3 and class.

Question 2.
State various operations that can be performed on a file and directory.
Answer:
Operations Performed on Files Using Java
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 :
    1. Determining the path of a file or a directory.
    2. Opening a file.
    3. Writing to a file.
    4. Reading from a file.
    5. Closing a file.
    6. Deleting a file.
    7. Querying the attributes of a file.
  • Java provides built-in classes that contain methods to help with these tasks.
  • 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 characters.

Computer Class 12 GSEB Solutions Chapter 11 File Handling

Question 3.
Why is the concept of Streams introduced in java, give the advantages of using streams.
Answer:
Introduction to Streams

  • To modify a file or display the contents of a file, the concept of streams has to be understood.
  • Java uses streams classes to carry out read and write operations on files. The types of input and output devices have to be revised.
  • For instance, keyboard is an input device while monitor is an output device.
  • Hard disk can be classified as both input and output device as data can be stored and read from the files.
  • There are various devices available in the market from different manufacturers and different capabilities.
    1. For example, hard disk are manufactured by various companies and come with different storage capacities like 500GB or 1 TB.
    2. Apart from this, hard disk can be connected using different cables like USB or SATA.
  • However, a Java programmer does not need to worry about the technical details like type of hard disk or its capacity while developing a program to perform read / write operations over the files.
  • This is possible because java language provides functionality of streams.
  • A stream is an abstract representation of an input or output device that is used as a source or destination for data.
  • Visualize a stream as a sequence of bytes that flows into the program or that flows out of the program. One can write data or read data using streams.
  • When data is written 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 :
    1. Programmer does not need to worry about the technical details of the device.
    2. The program can work for a variety of input / output devices without any changes to the source code.

Stream Classes in Java

  • To understand byte streams and character streams, one needs to differentiate between character and byte representation.
  • An example of number “5”, which can be represented in two different ways is shown in table.
Representation Particulars Binary Representation
Character 5 ASCII Value : 53 00110101
Binary number 5 Binary Value : 5 00000101

Table : Character and Binary Representation

  • A character is generally stored using ASCII or Unicode format but when it is used for calculation purpose and then its binary value is meaningful.
  • For example, the statement int i = 32; declares T as an integer type variable that stores number 32.
  • However 32 can be represented as two separate characters ’3’ and ’2’. The character representation is advisable when sentences are written like “Human beings have 32 teeth”.
  • In the above sentence there is no calculation required with the number. But when it is applied for numerical calculations, data types like int, float or double are used, that allows storing the numbers in binary format.
  • Java supports two types of streams byte stream and character stream.
  • Streams transfer data in the form of bytes to the file or devices are known as byte stream or binary stream.
  • The files that are created using byte stream are known as binary files. If variables are to be stored like integer, double or boolean into a file, then binary files should be used.
  • Binary files can also be used to store arrays or objects.
  • Similarly text files and program codes are created using character stream. They can be opened in text editors like vi and 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 while byte stream classes present in java.io package deal with binary data.
  • Figure shows the classification of stream classes.

Computer Class 12 GSEB Solutions Chapter 11 File Handling 1

 

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

Computer Class 12 GSEB Solutions Chapter 11 File Handling

Question 4.
Choose the most appropriate option from those given below:

1) Which of the following statements is true ?
(A) Volatile storage lasts only a few seconds.
(B) Volatile storage is lost when a computer is shutdown.
(C) Computer disks are volatile storage devices.
(D) All of the above are true.
Answer:
(B) Volatile storage is lost when a computer is shutdown.

2) Which of the following refers to a collection of data stored on a nonvolatile device in a computer system ?
(A) File
(B) Application
(C) Volatile data
(D) Hard-disk
Answer:
(A) File

3) The data hierarchy occurs in which of the following order from the smallest to largest piece of data ?
(A) file:character:field:record
(B) flle:character:record:field
(C) character:field:file:record
(D) character:field:record:file
Answer:
(D) character:field:record:file

4) Which of the following is true about streams ?
(A) Streams always flow in two directions
(B) Streams are channels through which the data flow
(C) Only one stream can be open in a program at a time.
(D) All of the above are true
Answer:
(C) Only one stream can be open in a program at a time.

5) Which of the following is used as a separator between fields of a record ?
(A) Path
(B) Delimiter
(C) Variable
(D) Space
Answer:
(B) Delimiter

6) Scanner class can be used to performing which of the following operations ?
(A) Accept input from the keyboard
(B) Read from the file
(C) Parse a string separated by delimiters
(D) All of the above
Answer:
(D) All of the above

Computer Class 12 GSEB Solutions Chapter 11 File Handling

Computer Class 12 GSEB Notes Chapter 11 File Handling

Storage Devices of Computer System
Storage devices of a computer can be broadly classified into two categories. (1) Volatile storage and (2) Non-volatile storage.
(1) Volatile storage :

  • Volatile storage is temporary. Values stored in variables are lost when a computer is shutdown.
  • A Java program that stores a value in a variable uses Random Access Memory (RAM). Apart from variables, objects and their references are generally stored in RAM.
  • Once the program terminates or the computer shuts down the data is lost.

(2) Non-volatile storage :

  • Non-volatile storage is permanent storage. Data is not lost when a computer loses power.
  • When a Java program is saved on a disk, it is using permanent storage.
  • A computer file is a collection of data stored on a non-volatile device. Files exist on permanent storage devices, such as hard disks, USB drives, optical disks and compact discs. Data stored in files is often called persistent data.

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 directions.
  • A programmer can create / rename / delete a file or a directory. The attributes of a file can also be accessed like its permissions, length of a file or last modification time.
  • 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 that can be used to perform various operations on a file or a directory.
  • However, 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

  • By using the File class, one can create a reference to any file by providing its absolute path in string format or by providing the relative path.
  • The File class provides following constructors to refer a file or a directory
    1. File (String path)
    2. File (String directory_path, String file_name)
    3. File (File directory, String file_name)
  • One can take an example for the above mentioned constructors.
  •  In Linux, “passwd” file present in “/etc” directory stores the information of the users existing in the system.
  • Suppose one wants to display its attributes, then its java file object can be created using three ways as mentioned below :
    1. By specifying the path as
      File fileobj = new File(“/etc/passwd”);
    2. By specifying directory and filename as two separate arguments
      File fileobj = new File(“/etc”, “passwd”);
    3. By using the reference to directory encapsulated in dirobj object
      File dirobj = new File)”/etc”);
      File fileobj = new File(dirobj, “passwd”);
  • Computer Class 12 GSEB Solutions Chapter 11 File Handling

Methods of File Class

  • The Table summarizes few widely used methods 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 exists or directory.
String getName( ) Returns the name of the file or directory referred by the object
String getPath( ) Returns the path to the file or directory
long length( ) Returns the number of bytes in that file.
String! ] list( ) Returns the name of the files and directories in a directory.
File[ ] listFiles( ) Returns an array of abstract pathnames denoting the files in the directory

Table : Few widely used method of File Class

  • After creating an object of file class that refers to a particular directory, one can use the list( ) method to list all the files present in that directory.
  • The program given in code listing demonstrates the listing of files present in “/home/Akash/ programs/files” directory.
  • In the program, a variable has been used to count ‘ the number of files and directories for a given directory, an array, listOfFiles of the File class and is used to store the file objects present in the directory.

Computer Class 12 GSEB Solutions Chapter 11 File Handling 2Computer Class 12 GSEB Solutions Chapter 11 File Handling 3

Computer Class 12 GSEB Solutions Chapter 11 File Handling 4

  • Note : The above code lists files and directories present in the “/home/Akash/programs/files” directory.

Computer Class 12 GSEB Solutions Chapter 11 File Handling

Character Stream Classes

  • Character stream classes are a group of classes available in java.io package. They can be used to read and write 16 bit Unicode characters.
  • Character stream classes can be further classified into Reader and Writer classes.
  • Reader classes are a group of classes designed to read characters from files. The Writer classes are a group of classes designed to write characters into a file.
  • Figure shows the hierarchy of Character Stream Classes.

Computer Class 12 GSEB Solutions Chapter 11 File Handling 5

  • As seen in the figure, java.io.Reader class and java.io.
  • Writer classes are inherited from the Object class.
  • They are abstract classes (classes that cannot be used to create an object) and come with set of methods to be implemented by its subclasses.
  • InputStreamReader and BufferedReader are the subclass of Reader Class.
  • FileReader class is the subclass of InputStreamReader class.
  • Similarly OutputStream Writer, BufferedWriter and PrintWriter are the subclasses of Writer class.
  • FileWriter class is the subclass of OutputStream Writer class.
  • A detailed description of methods, constructors can be obtained from the online Java documentation at http://docs.oracle.com/javase/ 6/docs/api.

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.
  • In the programs here, there is a usage of FileWriter class to perform write operations.
  • The methods of Writer class throw IOException occurs when there is a failed I/O operation.
  • IOException is a checked exception, so care must be taken of it olherwise there will be a compiling error. Table lists few of the methods ofWriter class; these methods are used by its subclasses.
Method Description
void close ( ) Closes the stream
void write (int c) Writes the lower 16 bits of ‘c’ to the stream
void write (String s) Writes string ‘s’ to the stream
  • The OutputStream Writer class extends Writer .class. It converts stream of characters to a stream of bytes.
  • The FileWriter class extends OutputStream Writer and outputs characters to a file.
  • Some of its constructors are :
    FileWriter (String filepath) throws IOException FileWriter (File fileobj) throws IOException FileWriter (String filepath, Boolean append) throws IOException
  • In the above constructors, the parameter filepath is the full path name of a file and fileobj is a file class object that describes the file.
  • In the last constructor, if append is true, characters are appended to the end of file, otherwise the existing contents of the file are overwritten.
  • For example an object of FileWriter can be created as shown below:
    FileWriter fwobject = new FileWriter (“/java/ files/Charfilel .txt”);
  • Below is an example that illustrates how to write to a file. Assume that the files are saved in the working directory.
  • The code listing shows how to create a file “Charfilel.txt” that does not exist.
  • Further, one can write few lines into that file using the write () method.
  • Methods like write() and close() used in this program are inherited from the Writer class.
    Output of the code listing is shown in figure, after execution of the program, one can use the cat command to display contents within the newly created file “Charfilel.txt”.

Computer Class 12 GSEB Solutions Chapter 11 File Handling 6Computer Class 12 GSEB Solutions Chapter 11 File Handling 7

  • It is important to close the stream object after writing to a file is accomplished.
  • Open files consume system resources and depending on the file mode, other programs may not be able to access them.
  • It’s important to close files as soon as the operations are over.

Computer Class 12 GSEB Solutions Chapter 11 File Handling 8

Computer Class 12 GSEB Solutions Chapter 11 File Handling

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 streams.
  • Use FileReader class in program to perform read operations.
  • Table lists few of the methods of Reader class;
  • These methods are used by its subclasses.
Method Description
void close () Closes the stream
int re ad() Reads next available character from the stream, it returns “-1” to indicate the end of stream.

Table 11.4 : Few methods of FileReader Class

  • The InputStreamReader class extends Reader class.
  • It converts a stream of bytes to a stream of characters.
  • The FileReader class extends InputStreamReader class and reads characters from a file.
  • Some of its constructors are :
    FileReader (String filepath) throws
    FileNotFoundException
    FileReader (File fileobj) throws
    FileNotFoundException
  • Object can be created of FileReader as shown below :
    FileReader frobject = new FileReader (“/java/ files/Charfile 1 .txt”);
  • In the program shown in code listing , there was an attempt to write to a file.
  • Now with this class one can write a program that reads from a file that has already been created.
  • The program shown in code listing , reads data from the file using read() method of FileReader class.
  • This read method is inherited from the Reader class.

Computer Class 12 GSEB Solutions Chapter 11 File Handling 9Computer Class 12 GSEB Solutions Chapter 11 File Handling 10

  • Figure shows the output of code listing.
  • Here it can be noted that the execution of program displays the output on the screen.
  • It displays all the contents of the file “Charfilel.txt”.

Computer Class 12 GSEB Solutions Chapter 11 File Handling 11

  • There is a special symbol to identify End of File (EOF).
  • While reading from a file, program must identify that the file has ended.
  • However the program reads from input stream so java read() method returns “-1” to identify the end of data in the stream.

Computer Class 12 GSEB Solutions Chapter 11 File Handling

Byte Stream Classes

  • From the above details, the process of characters using java.io package is understood.
  • Most of the real life applications require numeric calculations like storing the details of inventory in a file and calculating the costs involved or like storing the employee details and their salaries in a file.
  • For such kind of processing, java provides set of binary streams and their associated classes.
  • The FilelnputStream and FileOutputStream classes in the java.io package, gives the ability to read and write from and into files in the disk.
  • These classes are the sub-classes of InputStream and OutputStream classes.

(1) FileOutputStream :

  • The FileOutputStream is a subclass of OutputStream and is used to write bytes to the file or some output stream.
  • To use this class and its methods, first there is need to create a file, then use the write method derived from the abstract class OutputStream to write byte data into a file.
  • Few widely used methods of FileOutputStream classes are shown in table .
Method Description
void close( ) Closes the file output stream and releases any system resources associated with the stream.
void write (int b) Writes the specified byte to this file output stream.
void write (byte [ ] b) Writes b.length bytes from the specified byte array to this file output stream.

Table : Few methods of FileOutputStream Class

  • The constructors of FileOutputStream can accept either a string containing the path to the file location or an object of the File class.
  • Few of the constructors normally used are :
    FileOutputStream (String name) throws FileNotFoundException
    Or
    FileOutputStream (File file) throws
    FileNotFoundException
  • Examples of creating instances of
    FileOutputStream are as shown below :
    FileOutputStreamfosobject = new
    FileOutputStream (“/home/Akash/myfile.txt”);
  • Alternatively the following can also be used :
    File fobj = new File (“/home/Akash/myfile.txt”);
    FileOutputStreamfosobject = new
    FileOutputStream (fobj);
  • The above listed constructors can throw FileNotFoundException, if the file name refers to directory rather than a regular file, file does not exist, or file cannot be opened for some reason.

(2) FilelnputStream :

  • The FileOutputStream is a subclass of InputStream and is generally used to read byte data from the files.
  • It provides set of methods to perform write operations over the flies as shown in table 11.6.
Method Description
void close ( ) Closes the file input stream 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.

Table : Few methods of FilelnputStream Class

  • Below is a program that uses the above described classes to perform write and read operations over a file as shown in code listing.

Computer Class 12 GSEB Solutions Chapter 11 File Handling 12Computer Class 12 GSEB Solutions Chapter 11 File Handling 13

  • The program shown in code listing writes a string to a file “Binaryfile.dat”.
  • Later it creates an object of FilelnputStream to read the data from the same file and display it on the screen.
  • It must be noted in the above program, typecasting is applied to convert integer to character after read operation is performed.
  • Note : To observe the difference between text file and binary file, open the files created using the programs given in code listing.

Computer Class 12 GSEB Solutions Chapter 11 File Handling

Processing Input from Keyboard

  • In this section the different ways to input data to java program through the keyboard is explained.
  • A program can get input data from live interaction through keyboard / GUI or it may take input as command line arguments or from the files.
  • Although there are many classes that facilitate the input from keyboard, the most widely used technique – using scanner class of java.util package and using Console class of java.io package is explained below :

(1) Scanner Class :

  • Scanner class belongs to the java.util package.
  • It provides various 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 the default delimiter).
  • Each token can be of different type, for example a string like “India-1947” can also be read as “String-int” values.
  • Some related constructors and few methods of Scanner class are given below :
    Scanner (String str)
    Scanner (InputStream isobject)
    Scanner (File fobject) throws
    FileNotFoundException
  • A Scanner object can be created from a string, file object or InputStream object.
  • For instance the constructor can be used in the following way to read from a file and keyboard respectively :
    Scanner fileinput = new Scanner(new FileCStudents.dat”);
    Scanner kbinput = new Scanner(Systems.in);
  • Some of the important methods available with the Scanner class are listed in table 11.7.
Method Description
void close ( ) Closes the Scanner.
String next( ) Returns the next token
boolean hasNext( ) Returns true if there is a token in input.
int nextlnt ( ) 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

Table : Methods of Scanner Class

  • Below is a program that reads two numbers interactively from the user and displays the addition of those two numbers.
  • Code Listing shows the program :

Computer Class 12 GSEB Solutions Chapter 11 File Handling 14Computer Class 12 GSEB Solutions Chapter 11 File Handling 15

  • The code listing has created an object of . Scanner class.
  • The constructor of Scanner class accepts “System.in” as an argument so that it reads from the standard input (keyboard).
  • Both the numbers are scanned as integer numbers using the nextlntO method of the Scanner class.
    Figure shows the output of the program.

Computer Class 12 GSEB Solutions Chapter 11 File Handling 16

 

  • Scanner class can also be used to read from a file.
  • Check the example where the Scanner class is used to read the data from a file that contains information about few students.
  • In the example it is assumed that the file “Students.dat” already exists.
  • It contains five fields, student_no, student_name, marks of three subjects.
  • The format and data of the file Students.datais shown as below :
1. Akash 45 65 55
2. Badal 10 20 30
3. Zakir 45 40 60
4. David 65 50 75
  • Using this, a program can be written as shown in code listing, which reads the data of each student and performs operations like calculating the total marks and displaying them on the output.

Computer Class 12 GSEB Solutions Chapter 11 File Handling 17Computer Class 12 GSEB Solutions Chapter 11 File Handling 18

  • The output of the program is displayed on the monitor as shown in figure.

Computer Class 12 GSEB Solutions Chapter 11 File Handling 19
(2) Console Class :

  • Scanner class was used in the previous example to read user input.
  • Apart from the Scanner class, there is another class which can be used to get the input from the keyboard.
  • This class is especially used when the input is to be types in hidden form (characters must not be echoed on the screen).
  • The Console class provides a method for reading password.
  • When reading the password the user input will be hidden or not shown in the console screen.
  • And it will return an array of character as the return type.
  • The Console class belongs to java.io package.
  • Few widely used methods of Console are listed in table.
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, Object args) This method is used to write a formatted string to this console’s output stream using the specified format string and arguments.

Table : Few Methods of Console Class

  • The program shown in code listing demonstrates the use of Console class to read username and password, further, it validates the username and password are correct or not.

Computer Class 12 GSEB Solutions Chapter 11 File Handling 20

Computer Class 12 GSEB Solutions Chapter 11 File Handling

  • The output of the program is shown in figure.
  • There are two attempts to input the username and password.
  • In the first attempt the username is false and that is why it displays invalid username message.
  • In the second attempt, the correct username and password are entered.

Computer Class 12 GSEB Solutions Chapter 11 File Handling 21

  • The program can be extended to read list of users and match their passwords from a file in the presence of multi-user environment.
  • Apart from the various classes covered in this chapter, java provides classes to store and retrieve objects using files.
  • It also provides classes and methods to access a file randomly. The above examples of the methods are of sequential operations.
  • However, there are classes, which allow to directly jump to the nth record instead of accessing it sequentially.

Leave a Comment

Your email address will not be published. Required fields are marked *