0% found this document useful (0 votes)
8 views10 pages

BufferedReader Scanner Wrapper

The document provides an overview of Java's input/output (I/O) capabilities, detailing the use of streams, including byte and character streams, and their respective classes. It explains how to read from and write to the console and files using various classes such as BufferedReader, PrintWriter, FileInputStream, and Scanner. Additionally, it covers the concept of wrapper classes for primitive types, along with autoboxing and auto-unboxing features in Java.

Uploaded by

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

BufferedReader Scanner Wrapper

The document provides an overview of Java's input/output (I/O) capabilities, detailing the use of streams, including byte and character streams, and their respective classes. It explains how to read from and write to the console and files using various classes such as BufferedReader, PrintWriter, FileInputStream, and Scanner. Additionally, it covers the concept of wrapper classes for primitive types, along with autoboxing and auto-unboxing features in Java.

Uploaded by

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

Input/Output: Exploring java.

io
Most real applications of Java are not text-based, console programs. Rather, they are either
graphically oriented programs that rely on one of Java’s graphical user interface (GUI)
frameworks, such as Swing, the AWT, or JavaFX, for user interaction, or they are Web
applications.

Streams
Java programs perform I/O through streams. A stream is an abstraction that either produces
or consumes information. A stream is linked to a physical device by the Java I/O system. Java
implements streams within class hierarchies defined in the java.io package. Java also
provides buffer- and channelbased I/O, which is defined in java.nio and its subpackages.

Byte Streams and Character Streams


Java defines two types of streams: byte and character. Byte streams provide a convenient
means for handling input and output of bytes. Byte streams are used, for example, when
reading or writing binary data. Character streams provide a convenient means for handling
input and output of characters.

The Byte Stream Classes


Byte streams are defined by using two class hierarchies. At the top are two abstract classes:
InputStream and OutputStream are defined in java.io package. To use the stream
classes, you must import java.io. Two of the most important methods of InputStream and
OutputStream class are read( ) and write( ).

The Character Stream Classes


Character streams are defined by using two class hierarchies. At the top are two abstract
classes: Reader and Writer are defined in java.io package. Two of the most important
methods of Reader and Writer class are read( ) and write( ), which read and write
characters of data, respectively.

The Predefined Streams


All Java programs automatically import the java.lang package. This package defines a class
called System. System also contains three predefined stream variables: in, out, and err.
These fields are declared as public, static, and final within System. This means that they
can be used by any other part of your program and without reference to a specific System
object. System.out refers to the standard output stream. By default, this is the console.
System.in refers to standard input, which is the keyboard by default. System.err refers to
the standard error stream, which also is the console by default. System.in is an object of
type InputStream; System.out and System.err are objects of type PrintStream, these
are byte streams.

Reading Console Input


In Java, console input is read from System.in as byte stream. InputStreamReader, a
subclass of Reader class, is used to read input from System.in that convert the bytes into
character set and stored in a buffer. BufferedReader class is used to read from the
buffered character set.
The way to connect BufferedReader to keyboard is –
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);

After these statements executes, br is a character-based stream that is linked to the


console through System.in.

Reading Characters
To read a character from a BufferedReader, use read( ). It reads a character from the
input stream and returns it as an integer value. It returns –1 when the end of the stream is
encountered. No input is actually passed to the program until you press enter because
System.in is line buffered, by default.

Example
// Use a BufferedReader to read characters from the console.
// Save the file with name BrChrRead.java
import java.io.*;
class BrChrRead
{
public static void main(String args[]) throws IOException
{
char c;
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char)br.read();
System.out.println(c);
} while(c != 'q');
}
}

Reading Strings
To read a string from the keyboard, use the version of readLine( ) method of the
BufferedReader class.
Example
// Read a string from console using a BufferedReader.
import java.io.*;
class BRReadLines
{
public static void main(String args[]) throws IOException
{
// create a BufferedReader using System.in
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);

String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
do {
str = br.readLine();
System.out.println(str);
} while(!str.equals("stop"));
}
}

Writing Console Output


Console output is most easily accomplished with print( ) and println( ). For realworld
programs, the recommended method of writing to the console when using Java is through a
PrintWriter stream. PrintWriter is one of the character-based classes.
PrintWriter pw = new PrintWriter(System.out, true);
Here, true means Java flushes the output stream every time a println( ) or print( ) method
is called.
Example:
// Demonstrate PrintWriter
import java.io.*;
public class PrintWriterDemo {
public static void main(String args[]) {
PrintWriter pw = new PrintWriter(System.out, true);
pw.println("This is a string");
int i = -7;
pw.println(i);
double d = 4.5e-7;
pw.println(d);
}
}

Reading and Writing Files


We use two stream classes: FileInputStream and FileOutputStream, which create byte
streams linked to files. First you open a file to access it. The forms are:
FileInputStream(String fileName) throws FileNotFoundException
FileOutputStream(String fileName) throws FileNotFoundException
If the file does not exist, then FileNotFoundException is thrown.
FileNotFoundException is a subclass of IOException. When you are done with a file, you
must close it. This is done by calling the close( ) method. Closing a file releases the system
resources allocated to the file, allowing them to be used by another file. Failure to close a
file can result in “memory leaks” because of unused resources remaining allocated.

To read from a file, you can use read( ). It reads a single byte from the file and returns the
byte as an integer value. read( ) returns –1 when the end of the file is encountered.
Example: Read a file and display the contain on the screen using FileInputStream class.
import java.io.*;
class ReadFile{
public static void main(String[] gitam) {
//Open a file and read the contain of it.
try{
FileInputStream fin = new FileInputStream(gitam[0]);
int i;
do{
i=fin.read();
if(i!=-1) System.out.print((char)i);
}while(i!=-1);

fin.close();
} catch(IOException e){
System.out.println("Exception: " + e);
return;
}
}
}
Example: Read a file and display the contain on the screen using FileReader class.
import java.io.*;
class ReadFile{
public static void main(String[] gitam) {
//Open a file and read the contain of it.
try{
FileReader fin =new FileReader(gitam[0]);
BufferedReader br =new BufferedReader(fin);
int i;
do{
i=br.read();
if(i!=-1) System.out.print((char)i);
}while(i!=-1);

br.close();
} catch(IOException e){
System.out.println("Exception: " + e);
return;
}
}
}
Example: Copy a file using FileInputStream and FileOutputStream class
import java.io.*;
class CopyFile {
public static void main(String args[])
{
int i;
try {
// Attempt to open the files.
FileInputStream fin = new FileInputStream(args[0]);
FileOutputStream fout = new FileOutputStream(args[1]);
do {
i = fin.read();
if(i != -1) fout.write(i);
} while(i != -1);

fin.close();
fout.close();
} catch(IOException e) {
System.out.println("I/O Error: " + e);
}

}
}

Example: Copy a file using FileReader and FileWrite class


import java.io.*;
class CopyFile {
public static void main(String args[])
{
int i;
try {
// Attempt to open the files.
FileReader fin = new FileReader(args[0]);
FileWriter fout = new FileWriter(args[1]);
BufferedReader br = new BufferedReader(fin);
BufferedWriter bwr = new BufferedWriter(fout);
do {
i = br.read();
if(i != -1) bwr.write(i);
} while(i != -1);

br.close();
bwr.close();
} catch(IOException e) {
System.out.println("I/O Error: " + e);
}

}
}

Scanner
Scanner can be used to read input from the console, a file and it is the member of the
java.util package.
Scanner constructor to read from console:
Scanner sc = new Scanner(System.in);
Scanner that reads from a file:
FileReader fin = new FileReader("File Name with complete path");
Scanner src = new Scanner(fin);

Some useful method of Scanner class:


1. String next( ) -- Returns the next token of any type from the input source.
2. String nextLine( ) -- Returns the next line of input as a string.
3. boolean nextBoolean( ) -- Returns the next token as a boolean value.
4. byte nextByte( ) -- Returns the next token as a byte value.
5. short nextShort( ) -- Returns the next token as a short value.
6. int nextInt( ) -- Returns the next token as an int value.
7. long nextLong( ) -- Returns the next token as a long value.
8. double nextDouble( ) -- Returns the next token as a double value.
9. float nextFloat( ) -- Returns the next token as a float value.

Example: Read input from console using Scanner class.


/* Sample program to demonstrate how Scannener class is uesed to
....read information from console. Save the file with name ScannerDemo.java
*/
import java.util.*;
class ScannerDemo{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num;
System.out.println("Read an Integer: ");
num = sc.nextInt();
System.out.println("Value at num: " + num);

System.out.println("Read a sequence of Integers: ");


while(sc.hasNextInt()){
num = sc.nextInt();
System.out.println("Value at num: " + num);
}

String str;
System.out.println("Read a String: ");
sc.next();
str=sc.next();
System.out.println("String at str: " + str);

System.out.println("Read an entire line of String: ");


sc.nextLine();
str=sc.nextLine();
System.out.println("String at str: " + str);
}
}
Example: Read file using Scanner class.
import java.io.*;
import java.util.*;
class ReadFile{
public static void main(String[] gitam) {
//Open a file and read the contain of it.
try{
FileReader fin =new FileReader(gitam[0]);
//File fin =new File(gitam[0]);
Scanner sc =new Scanner(fin);
do{
if(sc.hasNextLine()) System.out.println(sc.nextLine());
}while(sc.hasNextLine());

sc.close();
} catch(IOException e){
System.out.println("Exception: " + e);
return;
}
}
}

Example: Copy a file using Scanner class.

import java.io.*;
import java.util.*;
class ScCopyFile{
public static void main(String[] gitam) {
//Open a file and read the contain of it.
try{
FileReader fin =new FileReader(gitam[0]);
//File fin =new File(gitam[0]);
Scanner sc =new Scanner(fin);
FileWriter fout = new FileWriter(gitam[1]);
do{
if(sc.hasNextLine()){
fout.write(sc.nextLine());
fout.write("\n");
}
}while(sc.hasNextLine());

sc.close();
fout.close();
} catch(IOException e){
System.out.println("Exception: " + e);
return;
}
}
}
Q1. Write a program to read 10 numbers in an array and calculate the average of it.

Wrappers
Use Objects, rather than Primitive types, would add an unacceptable overhead to even the
simplest of calculations. Thus, the primitive types are not part of the object hierarchy, and
they do not inherit Object. Despite the performance benefit offered by the primitive types,
there are times when you will need an object representation. For example, you can’t pass a
primitive type by reference to a method. Also, many of the standard data structures
implemented by Java operate on objects, which means that you can’t use these data
structures to store primitive types. To handle these (and other) situations, Java provides
type wrappers, which are classes that encapsulate a primitive type within an object.
There are eight wrapper classes for each primitive type, as mentioned below:

Constructors:
1. Character(char ch)
2. Boolean(boolean boolValue)
3. Integer(int intValue)
4. Short(short shortValue)
5. Duble(double doubleValue) etc

To get the primitive type value stored in the corresponding primitive object:
1. char charValue( ) - to obtain the char value
2. boolean booleanValue( ) - to obtain a boolean value
3. byte byteValue( ) - to obtain a byte value
4. double doubleValue( ) - to obtain a double value
5. float floatValue( ) - to obtain a float value
6. int intValue( ) - to obtain a int value
7. long longValue( ) - to obtain a long value
8. short shortValue( ) - to obtain a short value

Example:
// Demonstrate a type wrapper.
class Wrap {
public static void main(String args[]) {
Integer iOb = new Integer(100);
int i = iOb.intValue();
System.out.println(i + " " + iOb); // displays 100 100
}
}

Autoboxing and Auto-unboxing


Java added two important features: autoboxing and auto-unboxing.

Autoboxing is the process by which a primitive type is automatically encapsulated (boxed)


into its equivalent type wrapper whenever an object of that type is needed. There is no need
to explicitly construct an object.

Auto-unboxing is the process by which the value of a boxed object is automatically extracted
(unboxed) from a type wrapper when its value is needed. There is no need to call a method
such as intValue( ) or doubleValue( ).

With autoboxing, it is no longer necessary to manually construct an object in order to wrap a


primitive type. You need only assign that value to a type-wrapper reference. Java
automatically constructs the object for you. For example, here is the modern way to
construct an Integer object that has the value 100:
Integer iOb = 100; // autobox an int
Notice that the object is not explicitly created through the use of new. Java handles this for
you, automatically.

To unbox an object, simply assign that object reference to a primitive-type variable. For
example, to unbox iOb, you can use this line:
int i = iOb; // auto-unbox

Example 1:
// Demonstrate autoboxing/unboxing.
class AutoBox {
public static void main(String args[]) {
Integer iOb = 100; // autobox an int
int i = iOb; // auto-unbox
System.out.println(i + " " + iOb); // displays 100 100
}
}

Example 2:
// Autoboxing/unboxing takes place with
// method parameters and return values.
class AutoBox2 {
// Take an Integer parameter and return
// an int value;
static int m(Integer v) {
return v ; // auto-unbox to int
}
public static void main(String args[]) {
// Pass an int to m() and assign the return value
// to an Integer. Here, the argument 100 is autoboxed
// into an Integer. The return value is also autoboxed
// into an Integer.
Integer iOb = m(100);
System.out.println(iOb);
}
}

The below expression automatically unboxes iOb, performs the increment, and then reboxes the result
back into iOb.
++iOb;

Here, iOb is unboxed, the expression is evaluated, and the result is reboxed and assigned to iOb2.
iOb2 = iOb + (iOb / 3);

The same expression is evaluated, but the result is not reboxed.


i = iOb + (iOb / 3);

Converting Numbers to and from Strings


Example:
/* This program sums a list of numbers entered
by the user. It converts the string representation
of each number into an int using parseInt().
*/
import java.io.*;
class ParseDemo {
public static void main(String args[]) throws IOException {
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
int i;
int sum=0;
System.out.println("Enter numbers, 0 to quit.");
do {
str = br.readLine();
try {
i = Integer.parseInt(str);
} catch(NumberFormatException e) {
System.out.println("Invalid format");
i = 0;
}
sum += i;
System.out.println("Current sum is: " + sum);
} while(i != 0);
}
}

You might also like