3rd Chap-Streams
3rd Chap-Streams
class BRRead {
public static void main(String args[]) throws IOException
{
char c;
BufferedReader brob = new BufferedReader(new InputStreamReader
( System.in) );
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char) brob.read();
System.out.println(c);
} while(c != 'q');
}
}
• int read( ) throws IOException
• Each time that read( ) is called, 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.
Output:
Enter characters, 'q' to quit.
123abcq
1
2
3
a
b
c
q
System.in is line buffered, by default. This means that no input is
Reading Strings
• Readline(): To read a string from the keyboard, readLine( ) a member of the
BufferedReader class is used.
• String readLine( ) throws IOException
import java.io.*;
class BRReadLines {
public static void main(String args[]) throws IOException
{
// create a BufferedReader using System.in
BufferedReader brob = new BufferedReader (new InputStreamReader (System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
do {
str = brob.readLine();
System.out.println(str);
} while(!str.equals("stop"));
}
}
// A tiny editor.
import java.io.*;
class TinyEdit {
public static void main(String args[]) throws IOException
{
// create a BufferedReader using System.in
BufferedReader brob = new BufferedReader(new
InputStreamReader(System.in));
String str[] = new String[100];
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
For (int i=0; i<100; i++)
{
str[i] = brob.readLine();
If (str[i].equals("stop")) break;
}
System.out.println("\nHere is your file:");
// display the lines
for(int i=0; i<100; i++) {
if(str[i].equals("stop")) break;
System.out.println(str[i]);
}
}
Writing Console Output
• Console output is most easily accomplished
with print( ) and println( ). These methods are
defined by the class PrintStream (which is the
type of object referenced by System.out).
• PrintStream also implements the low-level
method write( ). Thus, write( ) can be used to
write to the console.
• void write(int byteval)
• Although byteval is declared as an integer,
only the low-order eight bits are written.
• . // Demonstrate System.out.write().
class WriteDemo {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}
• The PrintWriter class
• For real world 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 defines several constructors. One
among them is :
• PrintWriter(OutputStream outputStream,
boolean flushingOn)
• outputStream is an object of type OutputStream,
and flushingOn controls whether Java flushes the
output stream every time a println( ) method (among
others) is called.
• Writing Console Output
• PrintWriter supports the print( ) and println( )
methods. Thus, these methods can be used in the
same way as used them with System.out.
• If an argument is not a simple type, the PrintWriter
methods call the object’s toString( ) method and
then display the result.
The PrintWriter Class
// 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);
}
}
The output from this program is shown here:
This is a string
-7
Reading and Writing Files
• Two of the most often-used stream classes are FileInputStream
and FileOutputStream, which create byte streams linked to
files.
• The following are the constructors that will be using to create
objects of files
1. FileInputStream(String fileName) throws
FileNotFoundException
2. FileOutputStream(String fileName) throws
FileNotFoundException.
• The file must be closed by calling the close( ) method, which is
implemented by both FileInputStream and FileOutputStream.
• void close( ) throws IOException
• Closing a file releases the system resources allocated to the file,
allowing them to be used by another file.
Reading Files
• To read from a file: use read() which is defined
within FileInputStream.
• int read( ) throws IOException
• Each time that it is called, 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.
• It can throw an IOException.
• Writing Console Output
// Use it as : java ShowFile TEST.TXT try
import java.io.*; {
class ShowFile { do {
public static void main(String args[]) i = fin.read();
{ if(i != -1)
int i; System.out.print((char) i);
FileInputStream fin; } while(i != -1);
if(args.length != 1) }
{ catch(IOException e)
System.out.println("Usage: { System.out.println("Error Reading
ShowFile filename“ ); File"); }
return; try {
} fin.close();
Try }
{ // Attempt to open the file. catch(IOException e)
fin = new FileInputStream(args[0]); { System.out.println("Error Closing
} File");}
catch(FileNotFoundException e) }
{ System.out.println("Cannot Open }
File");
return; }
• Writing Console Output
// Use it as : java ShowFile TEST.TXT try {
import java.io.*; fin = new FileInputStream(args[0]);
class ShowFile { do {
public static void main(String args[]) i = fin.read();
{ if(i != -1) System.out.print((char) i);
int i; } while(i != -1);
FileInputStream fin = null; } catch(FileNotFoundException e) {
System.out.println("File Not Found.");
if(args.length != 1) { } catch(IOException e) {
System.out.println("Usage: ShowFile System.out.println("An I/O Error
filename"); Occurred");
return; } finally {
} // Close file in all cases.
// The following code opens a file, reads try {
characters until EOF if(fin != null) fin.close();
// is encountered, and then closes the } catch(IOException e) {
file via a finally block. System.out.println("Error Closing File");
}}}}
Writing Files
• To write to a file, use the write( ) method
defined by FileOutputStream.
• void write(int byteval) throws IOException
• This method writes the byte specified by
byteval to the file. Although byteval is
declared as an integer, only the low-order
eight bits are written to the file.
• If an error occurs during writing, an
IOException is thrown.
• Writing Console Output
Writing file:
// java CopyFile FIRST.TXT SECOND.TXT do {
import java.io.*; i = fin.read();
class CopyFile { if(i != -1) fout.write(i);
public static void main(String args[]) throws } while(i != -1);
IOException }
{ catch(IOException e) {
int i; System.out.println("I/O Error: " + e);
FileInputStream fin = null; } finally {
FileOutputStream fout = null; try {
if(args.length != 2) { if(fin != null) fin.close();
System.out.println("Usage: CopyFile from }
to"); catch(IOException e2) {
return; System.out.println("Error Closing I/pFile");
} }
try { try {
// Attempt to open the files. if(fout != null) fout.close();
fin = new FileInputStream(args[0]); }
fout = new FileOutputStream(args[1]); catch(IOException e2) {
System.out.println("Error Closing Output
File");
}}}}
Random access file operations
• It is a special kind of file which allows non-sequential or random
access to any location in file.
• Random Access File class is used for reading and writing to
random access file.
• RandomAccessFile class is part of Java IO.
• While creating the instance the mode to open the file is to be
specified. To open the file for read only mode use “r” and for
read-write operations use “rw”.
• The read write operations can be done by moving the file pointer
to any location . If end-of-file is reached before the desired
number of byte has been read then EOFException is thrown.
• Using file pointer, data can be read or write at any position. To get
the current file pointer, use getFilePointer() method and to set the
file pointer index, use seek(int i) method.
Random Access File Constructors:
1. RandomAccessFile(File file, String mode)
2. RandomAccessFile(String name, String mode)
• Few Methods used :
• getFilePointer(),seek(long pos), write(int b),
read(), readInt(), writeDouble(double v),
length(),close()
• To get the current file pointer getFilePointer()
and to set the file pointer index seek(int) is
used.
Random Access File operations
Import java.io.IOException;
Import java.io.RandomAccessFile;
public class RAFdemo
static final String Filepath=“input.txt”;
Public static void main(string args[])
{
try{
System.out.println(new String (readfrom(Filepath,1,18)));
Writeto(“TKRCET”);
}
Catch(IOException e)
{
e.printStackTrace();
}
}
}
private static byte[] readfrom(string Filepath,int
pos, int size) throws IOException
{
RandomAccessFile raf= new
RandomAccessFile(Filepath,r);
raf.seek(pos);
byte b[]=new byte[size];
raf.read(b);
raf.close();
return (b);
}
private static b[] writeto(string Filepath,string
data,int pos) throws IOException
{
RandomAccessFile raf= new
RandomAccessFile(Filepath,rw);
raf.seek(pos);
raf.write(data.getbytes[]);
raf.close();
}
Console class
• The Java Console class is used to get input from console.
It provides methods to read texts and passwords.
• The java.io.Console class is attached with system console
internally. The Console class is introduced since 1.5.
• Console supplies no constructors. Instead, a Console
object is obtained by calling System.console( ), which is
shown here:
static Console console( )
• If a console is available, then a reference to it is
returned. Otherwise, null is returned.
• Console is primarily a convenience class because most of
its functionality is available through System.in and
System.out.
import java.io.*; // Java Program to demonstrate Console Methods
class ConsoleDemo
{
public static void main(String args[])
{
String str;
//Obtaining a reference to the console.
Console con = System.console();
/ Checking If there is no console available, then exit.
if(con == null)
{ System.out.print("No console available");
return;
}
// Read a string and then display it.
str = con.readLine("Enter your name: ");
con.printf(“ your name is: %s\n", str);
}
//to read password and then display it
System.out.println("Enter the password: ");
char[] ch=con.readPassword();
//converting char array into string
String pass = String.valueOf(ch);
System.out.println("Password is: " + pass);
}
sample output:
Enter your name: TKRCET
your name is: TKRCET
Enter the password:
Password is: TKR
Serialization
• Serialization is the process of writing the state of an
object to a byte stream.
• At a later time, these objects can be restored by using
the process of deserialization.
• Serialization is a mechanism of converting the state of
an object into a byte stream.
• Deserialization is the reverse process where the byte
stream is used to recreate the actual Java object in
memory. This mechanism is used to persist the object.
• The byte stream created is platform independent. So,
the object serialized on one platform can be
deserialized on a different platform.
• A class must implement Serializable interface present
in java.io package in order to serialize its object
successfully
• The ObjectOutputStream class
contains writeObject() method for serializing an Object.
public final void writeObject(Object obj) throws
IOException.
• The ObjectInputStream class
contains readObject() method for deserializing an
object.
public final Object readObject() throws IOException,
ClassNotFoundException
• Advantages of Serialization
1. This is useful when you want to save the
state of your program to a persistent storage
area, such as a file.
2. To travel an object across a network.
3. to implement Remote Method Invocation
(RMI). RMI allows a Java object on one machine
to invoke a method of a Java object on a
different machine.
import java.io.*;
class MyClass implements Serializable {
String s;
int i;
double d;
public MyClass(String s, int i, double d) {
this.s = s;
this.i = i;
this.d = d;
}
public String toString() {
return "s=" + s + "; i=" + i + "; d=" + d;
}}
public class SerializationDemo {
public static void main(String args[]) {
// Object serialization
Try{
ObjectOutputStream objOStrm =
new ObjectOutputStream(new FileOutputStream("serial"))
// FileOutputStream fos = new FileOutputStream(“serial”);
//ObjectOutputStream objOStrm = new ObjectOutputStream
(fos);
MyClass object1 = new MyClass("Hello", -7, 2.7e10);
System.out.println("object1: " + object1);
objOStrm.writeObject(object1);
}
catch(IOException e) {
System.out.println("Exception during serialization: " + e);
}
// Object deserialization
Try{
ObjectInputStream objIStrm =
new ObjectInputStream(new FileInputStream("serial"))
Gen(T o) {
ob = o;
}
// Return ob.
T getob() {
return ob;
}
// Show type of T
void showType() {
System.out.println("Type of T is " + ob.getClass().getName());
}
}
• GenDemo {
class
public static void main(String args[]) {
Gen<Integer> iOb;
iOb = new Gen<Integer>(88);
iOb.showType();
int v = iOb.getob();
System.out.println("value: " + v);
System.out.println();
Gen<String> strOb = new Gen<String> ("Generics Test");
strOb.showType();
String str = strOb.getob();
System.out.println("value: " + str);} }
Output:
Type of T is java.lang.Integer
value: 88
Type of T is java.lang.String
value: Generics Test
Advantages:
1. A method/class/interface can be written
once and use for any type we want.
2. Generics make errors to appear compile
time than at run time
3. By using generics, we can implement
algorithms that work on different types of
objects and at the same they are type safe
too.