Built-In Input/Ouput Classes

Introduction

In Lesson 2, we introduced a class named Scanner. In our lessons so far, we were using this Scanner class to get values from the keyboard. The main reason we have been using Scanner is that it required a very short and simple introduction. In life, simplicity usually comes at a price. One of the limitations of the Scanner class is when it comes to reading a string in Microsoft Windows.

Fortunately, there are other classes you can use. That is, based on new topics we have studied so far (classes, construction, inheritance, abstraction, and exception handling), we can consider alternatives to the Scanner class.

Practical Learning Practical Learning: Introducing Built-In Input/Ouput Classes

  1. Create a new Java Application named DepartmentStore4
  2. To create a new class, in the Project window, right-click the DepartmentStore4sub-folder under DepartmentStore4 -> New -> Java Class
  3. Set the Class Name to StoreItem and click Finish
  4. Complete the class as follows:
    package departmentstore4;
    
    public class StoreItem {
        private long itemNumber;
        private String name;
        private String size;
        private double price;
    
        public StoreItem() {
            this.itemNumber = 0;
            this.name = "Unknown";
            this.size = "No Size";
            this.price  = 0.00;
        }
    
        // A constructor used to initialize an item
        public StoreItem(long number, String itemName,
                         String itemSize, double itemPrice) {
            this.itemNumber = number;
            this.name = itemName;
            this.size = itemSize;
            this.price  = itemPrice;
        }
    
        // A property for the stock number of an item
        public long getItemNumber() {
            return itemNumber;
        }
    
        public void setItemNumber(long itemNumber) {
            this.itemNumber = itemNumber;
        }
    
        // A property for the name of an item
        public String getName() {
            return name;
        }
    
        public void setName(String value) {
            this.name = value;
        }
    
        // A property for size of a merchandise
        public String getSize() {
            return size;
        }
    
        public void setSize(String value) {
            this.size = value;
        }
    
        // A property for the marked price of an item
        public double getUnitPrice() {
            return price;
        }
    
        public void setUnitPrice(double value) {
            if( this.price < 0)
                 this.price = 0.00;
            else
                 this.price = value;
        }
    }
  5. Access the Main.java file and change it as follows:
    package departmentstore4;
    import java.util.Scanner;
    
    public class Main {
        private static StoreItem create() {
            long number;
            String name;
            String size;
            double price;
            Scanner scnr = new Scanner(System.in);
            
            System.out.println("/-/Arrington Department Store/-/");
            System.out.print("Enter the Item #:     ");
            number = scnr.nextLong();
            System.out.print("Enter the Item Name:  ");
            name = scnr.nextLine();
            System.out.print("Enter the Item Size:  ");
            size = scnr.nextLine();
            System.out.print("Enter the Unit Price: ");
            price = scnr.nextDouble();
    
            StoreItem item = new StoreItem(number, name,
                                           size, price);
            return item;
        }
    
        private static void show(StoreItem si) {
            System.out.println("\n================================");
            System.out.println("/-/Arrington Department Store/-/");
            System.out.println("--------------------------------");
            System.out.println("Customer Invoice");
            System.out.printf("Item #:      %d\n", si.getItemNumber());
            System.out.printf("Description: %s\n", si.getName());
            System.out.printf("Item Size:   %s\n", si.getSize());
            System.out.printf("Unit Price:  %.2f\n", si.getUnitPrice());
            System.out.println("================================");
        }
        
        public static void main(String[] args) {
            StoreItem store = create();
            show(store);
        }
    }
  6. Execute the program
  7. Enter the item number as 860244 and press Enter
  8. Notice that you are not allowed to enter the item name.
    Enter the size as 11US | 10.5UK | 45EU and the price as 34.50
    /-/Arrington Department Store/-/
    Enter the Item #:    860244
    Enter the Item Name:  Enter the Item Size:  
    11US | 10.5UK | 45EU
    Enter the Unit Price: 545.95
    
    ================================
    /-/Arrington Department Store/-/
    --------------------------------
    Customer Invoice
    Item #:      860244
    Description: 
    Item Size:   11US | 10.5UK | 45EU
    Unit Price:  545.95
    ================================

Reading From a Stream

To provide support for the ability to read values from a stream (examples of streams are the keyboard or a file), the java.io package provides many classes. One of the main classes in this package is called Reader. Reader is an abstract class that most serves as a foundation for other classes that want to read characters from a stream.

Because it is abstract, you cannot declare a variable from the Reader class. Still, it is good to know that this class has two constructors whose syntaxes are:

protected Reader();
protected Reader(Object lock);

To support the ability to read a byte, the Reader class is equipped with a method named read. This method is overloaded with three versions. Of course, because Reader is abstract, classes derived from it must implement the read() method.

Input Stream Reading

Because Reader is abstract, many classes are derived from it, which allows them to customize their behavior. One of the most valuable operations you can perform on a stream is to read one or a group of characters. To support this operation, one of the classes derived from Reader is called InputStreamReader. In reality, theInputStreamReader class reads a byte and converts it into a character. By doing this repeatedly, it can read a series of bytes and convert that series into a group of characters, which ultimately results into a string.

The InputStreamReader class is equipped with two constructors. Their syntaxes are:

public InputStreamReader(InputStream in);
public InputStreamReader(InputStream in, String enc);

Therefore, before starting to read from an input stream, you can declare a variable of type InputStreamReader. Here is an example:

import java.io.*;

public class Exercise {    
    
    public static void main(String[] args) {
        InputStreamReader isr = new InputStreamReader(System.in);
    }
}

To provide the ability to read from a stream, the InputStreamReader class implements the read() method that it inherits from Reader. The Reader class provides two versions of the read() method.

Reading a Buffer

Introduction

After a Reader-based variable has read a byte and produced a character, or after getting one or a series of characters, they are assembled into a buffer. To read from this buffer, you would need another intermediary class. Fortunately, the java.io package provides a class namedBufferedReader. The BufferedReader class is derived from the Reader class.

Creating a Buffer Reader

To read from a buffer, you can declare a variable of type BufferedReader. The BufferedReaderclass is equipped with two constructors. Their syntaxes are:

public BufferedReader(Reader in);
public BufferedReader(Reader in, int sz);

As you can see, when declaring a BufferedReader variable, you must at least pass a Reader-based variable. For example, to read from the keyboard, you can pass a new instance of theInputStreamReader class. Here is an example:

import java.io.*;

public class Exercise {    
    
    public static void main(String[] args) {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
    }
}

Because the role of the InputStreamReader variable is to initialize the BufferedReader object, you do not have to first declare an InputStreamReader variable. You can pass the instead of theInputStreamReader class directly to the BufferedReader declaration. This could be done as follows:

import java.io.*;

public class Exercise {    
    
    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    }
}

When using the BufferedReader class, you must indicate that the method where it is used would throw an exception. This would be done as follows:

import java.io.*;

public class Exercise {    
    
    public static void main(String[] args) throws Exception {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(isr);
    }
}

Reading From a Buffer

One of the operations you can perform with a BufferedReader variable is to read a character. To support this, the BufferedReader class overrides the read() method that it inherits from theReader class.

Among the strengths of the BufferedReader class is its ability to read a line of text. To support this operation, the BufferedReader class is equipped with a method named readLine. Its syntax is:

public String readLine();

This method takes no argument. When it is called, it reads a line of text. A line of text is one or a group of characters starting from the left beginning and ends with a new line feed, a carriage return, or a linefeed. After performing its operator, this method produces the string it read.

After getting the line that was read, if you want to use it as a string, it is ready. Otherwise, you can convert it to the desired and appropriate value.

Practical Learning Practical Learning: Reading From a Buffer

  1. Change the Main.java file as follows:
    package departmentstore4;
    import java.io.*;
    
    public class Main {
    
        private static StoreItem create() throws Exception {
            long number;
            String strNumber;
            String name;
            String size;
            double price;
            String strPrice;
            BufferedReader in =
                    new BufferedReader(new InputStreamReader(System.in));
            
            System.out.println("/-/Arrington Department Store/-/");
            System.out.print("Enter the Item #:     ");
            strNumber = in.readLine();
            number = Long.parseLong(strNumber);
            System.out.print("Enter the Item Name:  ");
            name = in.readLine();
            System.out.print("Enter the Item Size:  ");
            size = in.readLine();
            System.out.print("Enter the Unit Price: ");
            strPrice = in.readLine();
            price = Double.parseDouble(strPrice);
            
            StoreItem item = new StoreItem(number, name,
                                           size, price);
            return item;
        }
    
        private static void show(StoreItem si) {
            System.out.println("\n================================");
            System.out.println("/-/Arrington Department Store/-/");
            System.out.println("--------------------------------");
            System.out.println("Customer Invoice");
            System.out.printf("Item #:      %d\n", si.getItemNumber());
            System.out.printf("Description: %s\n", si.getName());
            System.out.printf("Item Size:   %s\n", si.getSize());
            System.out.printf("Unit Price:  %.2f\n", si.getUnitPrice());
            System.out.println("================================");
        }
        
        public static void main(String[] args) throws Exception {
            StoreItem store = create();
            show(store);
        }
    }
  2. Execute the program
  3. Enter the item number as 860244 and press Enter
  4. Enter the item name as Italian Handcrafted Brown Wingtip Oxford Shoes and press Enter
  5. Enter the size as 11US | 10.5UK | 45EU and press Enter
  6. Enter the price as 545.95 and press Enter:
    /-/Arrington Department Store/-/
    Enter the Item #:     
    860244
    Enter the Item Name:  
    Italian Handcrafted Brown Wingtip Oxford Shoes
    Enter the Item Size:  
    11US | 10.5UK | 45EU
    Enter the Unit Price: 
    545.95
    
    ================================
    /-/Arrington Department Store/-/
    --------------------------------
    Customer Invoice
    Item #:      860244
    Description: Italian Handcrafted Brown 
    	     Wingtip Oxford Shoes
    Item Size:   11US | 10.5UK | 45EU
    Unit Price:  545.95
    ================================
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: