Lab Manual 09
Lab Manual 09
Lab Manual No 9
Dated:
24 July, 2017 to 29th July, 2017
th
Semester:
Spring 2017
134 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
Java I/O
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of stream to make I/O operation fast. The java.io package contains all the classes required for input and
output operations.
Stream
A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream because it is like a stream of water
that continues to flow.
In java, 3 streams are created for us automatically. All these streams are attached with console.
Let's see the code to print output and error message to the console.
5. System.out.println("simple message");
6. System.err.println("error message");
OutputStream vs InputStream
OutputStream
Java application uses an output stream to write data to a destination, it may be a file, an array, peripheral device or socket.
135 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING COMPUTER
ENGINEERING DEPARTMENT
InputStream
Java application uses an input stream to read data from a source, it may be a file, an array, peripheral device or socket.
Let's understand working of Java OutputStream and InputStream by the figure given below.
OutputStream class
OutputStream class is an abstract class. It is the super class of all classes representing an output stream of bytes. An output
stream accepts output bytes and sends them to some sink.
136 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
OutputStream Hierarchy
InputStream class
InputStream class is an abstract class. It is the super class of all classes representing an input stream of bytes.
137 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
InputStream Hierarchy
Method Description
protected void finalize() It is sued to clean up the connection with the file output stream.
void write(byte[] ary) It is used to write ary.length bytes from the byte array to the file output
stream.
void write(byte[] ary, int off, int len) It is used to write len bytes from the byte array starting at offset off to the
file output stream.
void write(int b) It is used to write the specified byte to the file output stream.
FileChannel getChannel() It is used to return the file channel object associated with the file output
stream.
FileDescriptor getFD() It is used to return the file descriptor associated with the stream.
void close() It is used to closes the file output stream.
138 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
Output:
Success...
testout.txt
import java.io.FileOutputStream;
public class FileOutputStreamExample{
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to File Handling.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
139 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
Method Description
int available() It is used to return the estimated number of bytes that can be read from the input
stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to b.length bytes of data from the input stream.
int read(byte[] b, int off, int len) It is used to read up to len bytes of data from the input stream.
long skip(long x) It is used to skip over and discards x bytes of data from the input stream.
FileChannel getChannel() It is used to return the unique FileChannel object associated with the file input
stream.
FileDescriptor getFD() It is used to return the FileDescriptor object.
protected void finalize() It is used to ensure that the close method is call when there is no more reference
to the file input stream.
void close() It is used to closes the stream.
140 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=fin.read(); // String First Chracter is Read
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
}
Note: Before running the code, a text file named as "testout.txt" is required to be created. In this file, we are having following
content:
After executing the above program, you will get a single character from the file which is 87 (in byte form). To see the text, you
need to convert it into character.
Output:
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
141 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer to store data. It adds more
efficiency than to write data directly into a stream. So, it makes the performance fast.
For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see the syntax for adding the buffer in an
OutputStream:
Constructor Description
BufferedOutputStream(OutputStream os) It creates the new buffered output stream which is used for writing the data to
BufferedOutputStream(OutputStream os, int size) It creates the new buffered output stream which is used for writing the data to
Method Description
void write(int b) It writes the specified byte to the buffered output stream.
void write(byte[] b, int off, int len) It write the bytes from the specified byte-input stream into a specified byte
array, starting with the given offset
void flush() It flushes the buffered output stream.
In this example, we are writing the textual information in the BufferedOutputStream object which is connected to the
FileOutputStream object. The flush() flushes the data of one stream and send it into another. It is required if you have connected
the one stream with another.
142 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout); String
s="Welcome to FileHandling.";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}
Java BufferedInputStream Class
Java BufferedInputStream class is used to read information from stream. It internally uses buffer mechanism to make the
performance fast.
5 When the bytes from the stream are skipped or read, the internal buffer automatically refilled from the contained
input stream, many bytes at a time.
Method Description
int available() It returns an estimate number of bytes that can be read from the input stream
without blocking by the next invocation method for the input stream.
int read() It read the next byte of data from the input stream.
int read(byte[] b, int off, int ln) It read the bytes from the specified byte-input stream into a specified byte array,
starting with the given offset.
void close() It closes the input stream and releases any of the system resources associated with
the stream.
void reset() It repositions the stream at a position the mark method was last called on this input
stream.
void mark(int readlimit) It sees the general contract of the mark method for the input stream.
143 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
long skip(long x) It skips over and discards x bytes of data from the input stream.
boolean markSupported() It tests for the input stream to support the mark and reset methods.
Methods
Method Description
Modifier and
Type
Writer append(char c) It appends the specified character to this writer.
Writer append(CharSequence csq) It appends the specified character sequence to this
writer
Writer append(CharSequence csq, int start, It appends a subsequence of the specified character
int end) sequence to this writer.
abstract void close() It closes the stream, flushing it first.
abstract void flush() It flushes the stream.
void write(char[] cbuf) It writes an array of characters.
abstract void write(char[] cbuf, int off, int len) It writes a portion of an array of characters.
void write(int c) It writes a single character.
void write(String str) It writes a string.
144 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
void write(String str, int off, int len) It writes a portion of a string.
import java.io.*;
}
Java Reader
Java Reader is an abstract class for reading character streams. The only methods that a subclass must implement are read(char[],
int, int) and close(). Most subclasses, however, will override some of the methods to provide higher efficiency, additional
functionality, or both.
Methods
Modifier and Type Method Description
abstract void close() It closes the stream and releases any system resources
associated with it.
void mark(int readAheadLimit) It marks the present position in the stream.
boolean markSupported() It tells whether this stream supports the mark() operation.
int read() It reads a single character.
int read(char[] cbuf) It reads characters into an array.
abstract int read(char[] cbuf, int off, int len) It reads characters into a portion of an array.
int read(CharBuffer target) It attempts to read characters into the specified character
buffer.
boolean ready() It tells whether this stream is ready to be read.
145 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
Example
import java.io.*;
public class ReaderExample {
public static void main(String[] args) {
try {
Reader reader = new FileReader("D:\\output.txt");
int data = reader.read();
while (data != -1) {
System.out.print((char) data);
data = reader.read();
}
reader.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
Java FileWriter Class
Java FileWriter class is used to write character-oriented data to a file. It is character-oriented class which is used for file
handling in java.
Unlike FileOutputStream class, you don't need to convert string into byte array because it provides method to write string
directly.
146 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
Method Description
void write(String text) It is used to write the string into FileWriter.
void write(char c) It is used to write the char into FileWriter.
void write(char[] c) It is used to write char array into FileWriter.
void flush() It is used to flushes the data of FileWriter.
void close() It is used to close the FileWriter.
import java.io.FileWriter;
public class FileWriterExample {
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("D:\\testout.txt");
fw.write("Welcome to Uet Taxila."); fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}
Java FileReader Class
Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class.
147 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
Method Description
int read() It is used to return a character in ASCII form. It returns -1 at the end of file.
void close() It is used to close the FileReader class.
import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
Java BufferedWriter Class
Java BufferedWriter class is used to provide buffering for Writer instances. It makes the performance fast. It inherits Writer
class. The buffering characters are used for providing the efficient writing of single arrays, characters, and strings.
Class declaration
Class methods
Method Description
void newLine() It is used to add a new line by writing a line separator.
void write(int c) It is used to write a single character.
void write(char[] cbuf, int off, int len) It is used to write a portion of an array of characters.
void write(String s, int off, int len) It is used to write a portion of a string.
void flush() It is used to flushes the input stream.
void close() It is used to closes the input stream
148 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
import java.io.*;
public class BufferedWriterExample {
public static void main(String[] args) throws Exception {
FileWriter writer = new FileWriter("D:\\testout.txt");
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write("Welcome to CPED.");
buffer.close();
System.out.println("Success");
}
}
Java BufferedReader Class
Java BufferedReader class is used to read the text from a character-based input stream. It can be used to read data line by line
by readLine() method. It makes the performance fast. It inherits Reader class.
Method Description
int read() It is used for reading a single character.
int read(char[] cbuf, int off, int len) It is used for reading characters into a portion of an array.
boolean markSupported() It is used to test the input stream support for the mark and reset method.
String readLine() It is used for reading a line of text.
boolean ready() It is used to test whether the input stream is ready to be read.
long skip(long n) It is used for skipping the characters.
void reset() It repositions the stream at a position the mark method was last called on this
input stream.
void close() It closes the input stream and releases any of the system resources associated
with the stream.
149 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
import java.io.*;
public class BufferedReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
BufferedReader br=new BufferedReader(fr);
int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fr.close();
}
String tokenization:
String tokenization is defined as the problem that consists of breaking up a string into tokens which are separated by delimiters.
Both tokens and delimiters are themselves strings. Commonly used string structures that require the use of string tokenization
are Common Separated Values (CSV), written text and basically any other format of data grouping where differing units of data
are separated by some kind of delimiter.
Assume you have data units representing fruit that are in a basket:
D Apple
E Peach
F Orange
G Banana
If you decided to package these data units and store them in a file, a simple conclusion would be concatenate all data units into
one large string. An example would be as follows:
ApplePeachOrangeBanana
The problem with this kind of formatting is that it may be simple producing the data string initially, but when the data needs to
be read back in and broken up into its independent data units, the problem of parsing the data, and determining where a
particular unit begins and where it ends becomes rather difficult.
150 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
Lab Task :
l) Write a program to take input string from user and tokenize the string using StringTokenizer object and delimiter.
Take delimiters from user.
m) Write a program to create file of your name. Write your name and roll number in it. Your program should also contain
statements for reading file.
n) Write a program that inputs words from the user and save the entered words,one word per line, in a text file. The
program terminates when the user enters the word STOP (case insensitive).
o) Solve the Level 1 Programming Exercise of Chapter 12 Page 725 .
p) Reading Chapter 12 .
151 | P a g e