0% found this document useful (0 votes)
22 views

Lab Manual 09

The document discusses Java I/O and describes input and output streams in Java. It provides examples of using FileOutputStream and FileInputStream classes to write and read from files.

Uploaded by

Zara
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Lab Manual 09

The document discusses Java I/O and describes input and output streams in Java. It provides examples of using FileOutputStream and FileInputStream classes to write and read from files.

Uploaded by

Zara
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA

FACULTY OF TELECOMMUNICATION AND INFORMATION


ENGINEERING COMPUTER ENGINEERING DEPARTMENT

Object Orienting Programming


(Java)

Lab Manual No 9

Dated:
24 July, 2017 to 29th July, 2017
th
Semester:
Spring 2017

Lab Instructor: SHEHARYAR KHAN Page 1

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.

We can perform file handling in java by Java I/O API.

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.

6. System.out: standard output stream

7. System.in: standard input stream

8. System.err: standard error stream

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");

Let's see the code to get input from console.

10. int i=System.in.read();//returns ASCII code of 1st character


11. System.out.println((char)i);//will print the character

OutputStream vs InputStream

The explanation of OutputStream and InputStream classes are given below:

OutputStream

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

Lab Instructor: SHEHARYAR KHAN Page 2

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.

Useful methods of OutputStream


Method Description
1) public void write(int)throws IOException is used to write a byte to the current output stream.
2) public void write(byte[])throws IOException is used to write an array of byte to the current output stream.
3) public void flush()throws IOException flushes the current output stream.
4) public void close()throws IOException is used to close the current output stream.

Lab Instructor: SHEHARYAR KHAN Page 3

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.

Useful methods of InputStream


Method Description
1) public abstract int read()throws IOException reads the next byte of data from the input stream. It returns -1 at the
end of file.
2) public int available()throws IOException returns an estimate of the number of bytes that can be read from
the current input stream.
3) public void close()throws IOException is used to close the current input stream.

Lab Instructor: SHEHARYAR KHAN Page 4

137 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT

InputStream Hierarchy

Java FileOutputStream Class


Let's see the declaration for Java.io.FileOutputStream class:

public class FileOutputStream extends OutputStream

FileOutputStream class methods

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.

Lab Instructor: SHEHARYAR KHAN Page 5

138 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT

Java FileOutputStream Example 1: write byte

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...

The content of a text file testout.txt is set with the data A.

testout.txt

Java FileOutputStream example 2: write string

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);}
}

Lab Instructor: SHEHARYAR KHAN Page 6

139 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT

Java FileInputStream Class


Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such
as image data, audio, video etc. You can also read character-stream data. But, for reading streams of characters, it is
recommended to use FileReader class.

Java FileInputStream class declaration

Let's see the declaration for java.io.FileInputStream class:

24 public class FileInputStream extends InputStream

Java FileInputStream class methods

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.

Lab Instructor: SHEHARYAR KHAN Page 7

140 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT

Java FileInputStream example 1: read single character

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:

Welcome to File Handling.

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:

Java FileInputStream example 2: read all characters

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);}
}

Lab Instructor: SHEHARYAR KHAN Page 8

141 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT

Java BufferedOutputStream Class

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:

OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\testout.txt"));

Java BufferedOutputStream class declaration

Let's see the declaration for Java.io.BufferedOutputStream class :

9 public class BufferedOutputStream extends FilterOutputStream

Java BufferedOutputStream class constructors

Constructor Description

BufferedOutputStream(OutputStream os) It creates the new buffered output stream which is used for writing the data to

the specified output stream.

BufferedOutputStream(OutputStream os, int size) It creates the new buffered output stream which is used for writing the data to

the specified output stream with a specified buffer size.

Java BufferedOutputStream class methods

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.

Example of BufferedOutputStream class:

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.

Lab Instructor: SHEHARYAR KHAN Page 9

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.

The important points about BufferedInputStream are:

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.

F When a BufferedInputStream is created, an internal buffer array is created.

Java BufferedInputStream class methods

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.

Lab Instructor: SHEHARYAR KHAN Page 10

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.

Example of Java BufferedInputStream


import java.io.*;
public class BufferedInputStreamExample{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Java Writer
It is an abstract class for writing to character streams. The methods that a subclass must implement are write(char[], int, int),
flush(), and close(). Most subclasses will override some of the methods defined here to provide higher efficiency, functionality
or both.

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.

Lab Instructor: SHEHARYAR KHAN Page 11

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.

Java Writer Example

import java.io.*;

public class WriteExample {


public static void main(String[] args) {
try {
Writer w = new FileWriter("D:\\output.txt");
String content = "I love my country";
w.write(content);
w.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}

}
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.

Lab Instructor: SHEHARYAR KHAN Page 12

145 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT

void reset() It resets the stream.


long skip(long n) It skips characters.

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.

Java FileWriter class declaration

Let's see the declaration for Java.io.FileWriter class:

8. public class FileWriter extends OutputStreamWriter

Lab Instructor: SHEHARYAR KHAN Page 13

146 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT

Methods of FileWriter class

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.

Java FileWriter Example

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.

It is character-oriented class which is used for file handling in java.

Java FileReader class declaration

Let's see the declaration for Java.io.FileReader class:

// public class FileReader extends InputStreamReader

Lab Instructor: SHEHARYAR KHAN Page 14

147 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT

Methods of FileReader class

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.

Java FileReader Example

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

Let's see the declaration for Java.io.BufferedWriter class:

// public class BufferedWriter extends Writer

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

Lab Instructor: SHEHARYAR KHAN Page 15

148 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT

Example of Java BufferedWriter

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.

Java BufferedReader class declaration

Let's see the declaration for Java.io.BufferedReader class:

e) public class BufferedReader extends Reader

Java BufferedReader class methods

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.

Lab Instructor: SHEHARYAR KHAN Page 16

149 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT

Java BufferedReader Example

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.

Lab Instructor: SHEHARYAR KHAN Page 17

150 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT

Lab Task :

g) Construct a class that has the following functionality:

a- Input string and store it in a file.


It prompts for two options:
1- Clear the file and store the new input string
2- Add data to existing file.

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 .

Lab Instructor: SHEHARYAR KHAN Page 18

151 | P a g e

You might also like