• UNIT 12 : IO AND JAVA

    Key Unit Competency: to be able to use stream, reader and writer in java

    Introductory activity

    Teacher Ntwari prepared examination at the District level and he saved the examination in My Documents folder under File name” district Examination”. One of the questions is to calculate the following quadratic equation x2-7x=0

    1. Explain the path that should be used to access the file contents.

    2. Solve the above quadratic equations using java programming language.

    3. How many variables needed to solve the above quadratic equation if you need to run it with java programming language?

    12.1. Introduction to IO Streams

    Learning activity 12.1

    1. Discuss the steps to be followed if you are requested to write a program that will calculate and display the sum of 10 numbers that you need to provide during the execution of the program.

    The term stream refers to a sequence of values from any input source of data (key-board, file, port, and so on), or to any output destination for data (screen, file, port, and so on).

    They are,

    1. Byte Stream : It provides a convenient means for handling input and output of byte.

    2. Character Stream : It provides a convenient means for handling input and output of characters.

    12.1.1.Definition of Input Stream

    The Input Stream is an abstract class that describes stream input. In Java programming language the Input Stream is used to read data from a source.

    This class defines several methods among which include read() that reads byte of data

    12.1.2.Definition of Output Stream

    Output stream is an abstract class that describes stream output. In Java programming language, the Output Stream is used for writing data to a destination.This class defines several methods among which include write() that reads byte of data

    12.1.3 Role of I/O Stream

    IO Streams provide convenient ways of handling data input and output in a java program. While writing java programs, three IO objects are provided implicitly for performing data Input and Output.

    They are;

    • System.in (input stream)

    • System.out (output stream for normal results)

    • System.err (output stream for error messages)Generally System.in is connected to the keyboard and inputs character data*, and System.out and System.err are connected to the monitor and output character data.

    Application activity 12.1

    1. What is a stream and what are the types of Streams and classes of the Streams?

    2. Differentiate the following terms:

    a. System.in and System. out

    b. output stream and input stream

    12.2. Input Stream, Output Stream and File Stream

    Learning activity 12.2

    From the previous lessons in this unit, we have learned the standard I0 stream in Java. Write and Discuss in groups the source code program allows user to calculate area of any given triangle if base and height that are entered through the keyboard and print the area

    The goal of Input Stream and Output Stream is to abstract different ways to input and output: whether the stream is a file, a web page, or the screen shouldn’t matter. All that matters is that information is received from the stream (or send information into that stream.)

    12.2.1 Output Stream

    Java application uses an output stream to write data to a destination, it may be a file, an array, peripheral device or socket.

    Code of Printing “WELCOME WORLD” without advancing to a new line

    System.out.print(“ WELCOME WORLD”);

    Code of Printing “WELCOME WORLD “ and advance to a new line.

    System.out.println(“ WELCOME WORLD”);


    12.2.2. Input Stream

    Java application uses an input stream to read data from a source, it may be data, a file, and an array. There are different input stream classes that can be applied to input data from user.

    • scanner()

    • BufferedReader()

    • DataInputSteam()

    a. Using Scanner class.

    Java has a number of predefined classes which can be used. Predefined classes are organized in the form of packages. A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations) providing access protection and namespace management.

    In Java, data can be input with the help of the Scanner class. This Scanner class is found in java.util package. So, to use the Scanner class, java.util package needs to be included first in the program. Apackage is included in a program with the help of import keyword. The java.util.Scanner class or the entire java.util package are then imported.

    The advantage of using Scanner class is that it provides convenient methods for capturing primitives (nextInt(), nextFloat(), ...) from input devices whereas its disadvantage is that reading methods are not synchronized .

    To import a class or a package, one of the following lines should be added to the very be-ginning of the code.

    import java.util.Scanner; // This will import just the Scanner class

    import java.util.*; // This will import the entire java.util package

    After importing, the following statement will be valid when written in the program.

    Scanner k = new Scanner (System.in);Scanner k, here K is declared as an object of Scanner class. System.in within the round brackets tells Java that this will be System Input i.e. input will be given to the system.

    The main purpose of the Scanner class is to parse primitive types and strings using regular expressions, however it can also be used to read input from the user in the command line. Here is an example:

    Example 1: a program that asks to enter numbers from the keyboard and displays those numbers on the screen

    n= s1.nextInt(); s1.nextInt() will take integer input from the user and it assigns it to n. . So, this statement will be like n = 14; when user entered 14.

    Similarly, values of other data types can be also input . Same as nextInt() is used to input an integer value, other methods s in table 12.1 will be used to input those values.

    b. Using Buffered Reader Class

    Java Buffered Reader class is used to read the text from a character-based input stream. It can be used to read data line by line by read Line() method. It makes the performance fast. It inherits Reader class.

    Buffered Reader reader = new Buffered Reader(new Input Stream Reader(System.in));

    System.out.print(“Enter your name: “);

    String name = reader.read Line();

    System.out.println(“Your name is: “ + name);

    In the above example, the readLine() method reads a line of text from the command line.

    Advantages: The input is buffered for efficient reading and its disadvantage is that the wrapping code is hard to remember.

    Example of program using Buffered Reader


    Notice that a “keyboard object” for reading from the console keyboard can therefore be instantiated as follows:

    InputStreamReader inStream = new InputStreamReader(System.in);

    BufferedReader keyboard = new BufferedReader(inStream);

    The intermediate variable inStreamcould be eliminated and it can be done in one step like this:

    BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));

    c. Data Input Stream

    InputStream uses read Line() method of DataInputStream to read data from the keyboard. Java InputStreams are used for reading byte based data, one byte at a time.

    The following example describes how to use datainputstream wtih different data types

    Example 1


    Example 2


    Explanations:

    The readLine() method of DataInputStream reads a line at a time and returns a string, irrespective of what the line contains. Depending on the input value, the string is to be parsed into an int or double etc. This is extra work in the keyboard reading when compared to C/C++. In C/C++, parsing is done implicitly by %d, %f, etc.

    What is “System.in”?

    “ in” is an object of “ InputStream” class defined in System class (like “out” is an object of PrintStream class defined in System class). It is declared as static and final object. The in ob-ject is connected implicitly to the “ standard input stream” of the underlying OS.

    DataInputStream dis = new DataInputStream(System.in);

    System.in is a byte stream which is automatically connected to the keyboard reading mech-anism of operating system. It is chained to DataInputStream to facilitate the reading of user input with its readLine() method.

    Like System.in is connected to the keyboard mechanism of OS, the System.out is connected to the standard output mechanism of OS.

    Application Activity 12.2

    1. Write a java program that allows the user to enter three integers and that displays their sum

    2. Write a java program asking the user to enter a number and print its factorial.

    3. Write a java program that allows the user to enter the age of KARENZI, SINGIZWA and MPORE and print the youngest ( use Scanner , input stream and console)

    12.3 File Streams


    a. 1 File Input Stream

    This File Input Stream is used for reading data from the files. Objects can be created using the keyword new and there are several types of constructors available.

    The following constructor takes a file name as a string to create an input stream object to read the file:

    InputStreamf=newFileInputStream(“C:/java/hello”);

    The following constructor takes a file object to create an inputstream object to read the file.

    First a file object using File()methods created as follows:

    Filef=newFile(“C:/java/hello”);

    InputStreamf=newFileInputStream(f );

    Once Input Stream object i s in hand, then there is a list of helper methods which can be used to read from the stream or to do other operations on the stream.

    Methods used for file Input Stream

    1. public void close() throws IO Exception{}: This method closes the file output-stream. Releases any system resources associated with The file. Throws an IO Exception

    2. protected void finalize()throws IO Exception{}: This method cleans up the connection to the file. It ensures that the close method of this file output stream is called when there are no more references to this stream. It throws an 10 Exception.

    3. public intread(intr)throws IO Exception{}: This method reads the specified byte of data from the InputStream and returns the next byte of data and-1will be returned if it is end of file.

    4. public intread(byte[]r)throws IO Exception{}: This method reads r.length bytes from the inputstream into an array. I t r eturns the total number of bytes read. If end of file -1 will be returned.

    5. Public int available() throws IO Exception{}: Gives the number of bytes that can be read from this file input stream. It returns an integer.

    12.3.1 File Output Stream:

    File Output Stream is used to create a file and write data into it. The stream would create a file, if it doesn’t already exist, before opening it for output.

    a. File output stream constructors

    The following constructor takes a file name as a string to create an output stream object to write the file:

    OutputStream f=new FileOutputStream(“C:/java/hello”)

    The following constructor takes a file object to create an outputstream object to write the file. First, a file object using File()method is created as follows:

    Filef=newFile(“C:/java/hello”);

    OutputStream f=newFileOutputStream(f );

    Once the OutputStream object is in hand,then there is a list of helper methods,which can be used to write to stream or to do other operations on the stream.

    b. File output stream methods

    1. public void close() throws IO Exception{}: This method closes the file output stream. Releases any system resources associated with the file.Throws an IO Exception.

    2. protected void finalize()throws IO Exception{}: This method cleans up the connection to the file. Ensures that the close method of this file output stream is called

    Unit11: OOP AND JAVAASSESSMENT