Object Oriented Programming: Unit IV: I/O, Generics, String Handling

Reading and Writing Files

Methods, Purpose with Example Java Programs

InputStream is an abstract class for streaming the byte input. OutputStream is an abstract class for streaming the byte output. All these methods under this class are of void type.

Reading and Writing Files

InputStream is an abstract class for streaming the byte input. Various methods defined by this class are as follows.

OutputStream is an abstract class for streaming the byte output. All these methods under this class are of void type. Various methods defined by this class are as follows

FileInputStream / FileOutputStream

The FileInputStream class creates an InputStream using which we can read bytes from a file. The two common constructors of FileInputStream are -

FileInputStream(String filename);

FileInputStream(File fileobject);

In the following Java program, various methods of FileInputStream are illustrated -

Java Program[FileStream Prog.java]

import java.io.*;

class FileStreamProg

{

public static void main(String[] args) throws Exception

{

int n;

InputStream fobj = new FileInputStream("f:/I_O_programs/FileStreamProg.java");

System.out.println("Total available bytes: "+(n=fobj.available()));

int m=n-400;

System.out.println("\n Reading first "+m+" bytes at a time");

for(int i=0;i<m;i++)

System.out.print((char)fobj.read());

System.out.println("\n Skipping some text");

fobj.skip(n/2);

System.out.println("\n Still Available: "+fobj.available());

fobj.close();

}

}

Output

The FileOutputStream can be used to write the data to the file using the OutputStream. The constructors are -

FileOutputStream(String filename)

FileOutputStream(Object fileobject)

FileInputStream(String filename, boolean app);

FileInputStream(String fileobject,boolean app);

The app denotes that the append mode can be true or false. If the append mode is true then you can append the data in the file otherwise the data can not be appended in the file.

In the following Java program, we are writing some data to the file.

Java Program[FileOutStream Prog.java]

import java.io.*;

class FileOutStreamProg

{

public static void main(String[] args) throws Exception

{

String my_text="India is my Country\n" +"and I love my country very much.";

byte b[]=my_text.getBytes();

OutputStream fobj = new FileOutputStream("f:/I_O_programs/output.txt");

for(int i=0;i< b.length;i++)

fobj.write(b[i]);

System.out.println("\n The data is written to the file");

fobj.close();

}

}

Output

Ex. 4.3.1: Write a program that copies the content of one file to another by removing unnecessary spaces between words

Sol. :

import java.io.*;

public class CopyFile

{

private static void CopyDemo(String src, String dst)

{

try

{

File f1 = new File(src);

File f2 = new File(dst);

InputStream in = new FileInputStream(f1);

OutputStream out = new FileOutputStream(f2);

byte[] buff

int len;

= new byte[1024];

len=in.read(buff);

while (len > 0)

{

String text=new String(buff);//converting bytes to text

text text.replaceAll("\\s+", "");//removing unnecessary spaces

buff=text.getBytes();//converting that text back to bytes

out.write(buff,0,len);//writing bytes to destination file

len=in.read(buff);//reading the remaining content of the file

}

in.close();

out.close();

System.out.println("File copied.");

}

catch (FileNotFoundException ex)ynod

{

System.out.println(ex.getMessage() + " in the specified directory.");

System.exit(0);

}

catch (IOException e)

{

System.out.println(e.getMessage());

}

}

public static void main(String[] args)

{

CopyDemo(args[0], args[1]);

}

}

Output

D:\test>javac CopyFile.java

D:\test>javac CopyFile.java

D:\test>java CopyFile in.txt out.txt

File copied.

D:\test>type in.txt

This is my India.

I love my country.

D:\test>type out.txt

This is my India. I love my country.

FilterInputStream / FilterOutputStream

FilterStream class are those classes which wrap the input stream with the byte. That means using input stream you can read the bytes but if you want to read integers, doubles or strings you need to a filter class to wrap the byte input stream.

The syntax for FilterInputStream and FilterOutputStream are as follows-

FilterOutputStream(OutputStream o)

FilterInputStream(InputStream i)

The methods in the Filter stream are similar to the methods in InputStream and OutputStream

DataInputStream / DataOutputStream

DataInputStream reads bytes from the stream and converts them into appropriate primitive data types whereas the DataOutputStream converts the primitive data types into the bytes and then writes these bytes to the stream. The superclass of DataInputStream class is FilterInputStream and superclass of DataOutputStream class is FilterOutputStream class. Various methods under these classes are


Let us see how these methods can be used in a Java Program -

Java Program[DataStream Prog.java]

import java.io.*;

class DataStream Prog

{

public static void main(String[] args) throws Exception

{

DataOutputStream obj=new DataOutputStream gibi mene(new FileOutputStream("in.txt"));

obj.write UTF("Archana");

obj.writeDouble(44.67);

obj.writeUTF("Keshavanand");

obj.writeInt(77);

obj.writeUTF("Chitra");

obj.writeChar('a');

obj.close();

DataInputStream in=new DataInputStream(new FileInputStream("in.txt"));

System.out.println("\nFollowing are the contents of the 'in.txt' file");

System.out.println(in.readUTF()+":"+in.readDouble());

System.out.println(in.readUTF()+":"+in.readInt());

System.out.println(in.readUTF()+":"+in.readChar());

}

}

Output

Program explanation

Note that in above program, along with other simple read and write methods we have used readUTF and writeUTF methods. Basically UTF is an encoding scheme that allows systems to operate with both ASCII and Unicode. Normally all the operating systems use ASCII and Java uses Unicode. The writeUTF method converts the string into a series of bytes in the UTF-8 format and writes them into a binary stream. The readUTF method reads a string which is written using the write UTF method.

BufferedInputStream / BufferedOutputStream

The BufferedInputStream and BufferedOutputStream is an efficient class used for speedy read and write operations. All the methods of BufferedInputStream and BufferedOutputStream class are inherited from InputStream and OutputStream classes. But these methods add the buffers in the stream for efficient read and write operations. We can specify the buffer size otherwise the default buffer size is 512 bytes.

In the following Java program the BufferedInputStream and BufferedOutputStream classes are used.

Java Program [Buffered Stream Prog.java]

import java.io.*;

class BufferedStreamProg

{

public static void main(String[] args)throws Exception

{

DataOutputStream obj=new DataOutputStream(new BufferedOutputStream(new FileOutputStream("in.txt")));

obj.writeUTF("Archana");

obj.writeDouble(44.67);

obj.writeUTF("Keshavanand");

obj.writeInt(77);

obj.writeUTF("Chitra");

obj.writeChar('a');

obj.close();

DataInputStream in=new DataInputStream(new BufferedInputStream(new FileInputStream("in.txt")));

System.out.println("\nFollowing are the contents of the 'in.txt' file");

System.out.println(in.readUTF()+":"+in.readDouble());

System.out.println(in.readUTF()+":"+in.readInt());

System.out.println(in.readUTF()+":"+in.readChar());

}

}

Program Explanation

This program is similar to the Java program we have discussed in section 5.4.2.1. The only change is we have added buffers. The creation of buffers is shown by the bold faced statements in above program.

Programming Example on Reading and Writing Files

Ex. 4.3.2: Write a program to replace all "word1" by "word2" from a file 1, and output is written to file2 file and display the number of replacement.

Sol. :

import java.io.*;

import java.util.*;

class FileDemo

{

public static void main(String[] args) throws Exception

{

int count=0;

File fin=new File("C:/lab/word.txt");

BufferedReader br=new BufferedReader(new FileReader(fin));

String FullStr=""";

String TempStr;

while((TempStr= br.readLine())!=null)//if multi-line input is present in the file //then it is collected in one string separated by spaces

{

FullStr+TempStr+"";

}

Scanner input=new Scanner(System.in);

System.out.print("Enter the word to be searched from the file: ");

String word1=input.next();

String Word_List[]=FullStr.split(" ");//Extract words from string for counting

//Searching for the word1

//no.of occurrences

for(int i=0;i<Word_List.length;i++)

{

if(Word_List[i].equals(word1))

{

count++; //counting no. of occurrences

}

}

System.out.print("\nEnter new Word for replacement: ");

String word2=input.next();

String New_Str=FullStr.replace(word1, word2);

//File is opened for writing purpose

File fout=new File("C:/lab/Newword.txt");

BufferedWriter bw=new BufferedWriter(new FileWriter(fout));

//Modified contents are written to the file

bw.write(New_Str);

System.out.println("\n The replacement is done and file is rewritten");

System.out.println("\nThe number of replacements are "+count);

bw.close();

br=new BufferedReader(new FileReader(fout));

System.out.println("\n Now, the Contents of the file are...\n");

while((TempStr= br.readLine())!=null)

System.out.println(TempStr);

br.close();

}

}

******************************

<word.txt>

******************************

PHP is fun.

Programming in PHP is interesting.

People love PHP

Output

Enter the word to be searched from the file: PHP

Enter new Word for replacement: Java

The replacement is done and file is rewritten

The number of replacements are 3

Now, the Contents of the file are...

Java is fun. Programming in Java is interesting. People love Java

Ex. 4.3.3 Write a program to replace all "word1" by "word2" to a file without using temporary file and display the number of replacement.

Sol.:

import java.io.*;

import java.util.*;

class FileDemo

{

public static void main(String[] args) throws Exception {

int count=0;

File fname=new File("C:/lab/word.txt");

BufferedReader br=new BufferedReader(new FileReader(fname));

String FullStr="";

String TempStr;

while((TempStr= br.readLine())!=null)//if multi-line input is present in the file //then it is collected in one string separated by spaces

{

FullStr+TempStr+"";

}

Scanner input=new Scanner(System.in);

System.out.print("Enter the word to be searched from the file: ");

String word1=input.next();

String Word_List[]=FullStr.split(" ");//Extract words from string for counting

//no.of occurrences

//Searching for the word1

for(int i=0;i<Word_List.length;i++)

{

if(Word List[i].equals(word1))

{

count++; //counting no. of occurrences

}

}

System.out.print("\nEnter new Word for replacement: ");

String word2=input.next();

String New_Str=FullStr.replace(word1,word2);

//File is opened for writing purpose

BufferedWriter bw=new Buffered Writer(new FileWriter(fname)); //Modified contents are written to the file

bw.write(New_Str);

System.out.println("\n The replacement is done and file is rewritten");

 System.out.println("\nThe number of replacements are "+count);

bw.close();

br=new BufferedReader(new FileReader(fname));

System.out.println("\n Now, the Contents of the file are...\n");

while((TempStr=br.readLine())!=null)

System.out.println(TempStr);

br.close();

}

Ex. 4.3.4 Write a program that takes input for filename and search word from command-line arguments and checks whether that file exists or not. If exists, the program will display those lines from a file that contains given search word.

Sol. :

import java.io.*;

class WordSearchDemo

{

public static void main(String args[]) throws IOException

{

boolean status;

boolean WordOccur=false;

File fobj = new File(args[0]);

if(fobj.exists())

status = true;

else

{

status=false;

System.out.println("\n This file does not exist!!!");

return;

}

if(status)

{

BufferedReader in = new BufferedReader(new FileReader(fobj));

String Line;

String key = args[1];

while ((Line = in.readLine()) != null)

{

String[] Data = Line.split(" ");

for(String Element:Data)

{

if(Element.equalsIgnoreCase(key))

{

System.out.println("""+key+' + "is present in the line + Line+""");

WordOccur = true;

}

}

}

if(!WordOccur)

System.out.println("This Word is not present in the Input File");

}

}

}

Output

E:\test\src>javac WordSearchDemo.java

E:\test\src>java WordSearchDemo input.dat java

'java' is present in the line 'learn Java Programming.'

Ex. 4.3.5 Write a program that counts the no. of words in a text file. The file name is passed as a command line argument. The program should check whether the file exists or not. The words in the file are separated by white space characters.

Sol. :

import java.io.*;

import java.util.*;

public class WordCountDemo

{

public static void main(String[] args) throws NullPointerException, IOException

{

try

{

BufferedReader in = new BufferedReader(new FileReader(args[0]));

String New Line = Word = "";

int Word Count = 0;

while ((New_Line = in.readLine()) != null)

Word += New Line + "";

StringTokenizer Token = new StringTokenizer(Word);

while (Token.hasMoreTokens())

{

String s = Token.nextToken();

Word_Count++;

}

System.out.println("Text file contains " + Word_Count + "words.");

}

catch (NullPointerException e)

{System.out.println("NULL PointerError: "+e.getMessage());}

catch (IOException e)

{System.out.println("IO Error: " + e.getMessage());}

}

}

<input.txt>

Hello Friends

It is very interesting to

learn Java Programming.

Output

E:\test\src>javac WordCountDemo.java

E:\test\src>java WordCountDemo input.txt

Text file contains 10 words.

Ex. 4.3.6 Write a program to count the total no. of chars, words, lines, alphabets, digits, white spaces in a given file.

Sol. :

import java.lang.*;

import java.io.*;

import java.util.*;

class WordCount

{

public static void main(String arg[]) throws Exception

{

int char_count=0;

int word_count=0;

int line_count=0;

int wspace_count=0;

int digit_count=0;

int alphabet_count=0;

String fname;

String temp_str;

StringTokenizer token;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter filename: ");

fname=br.readLine();

br=new BufferedReader(new FileReader(fname));

while((temp_str = br.readLine())!=null)

{

line_count++;

for(int i = 0; i < temp_str.length(); i++)

{

if(Character.is Whitespace (temp_str.charAt(i)))

wspace_count++;

if(Character.isDigit(temp_str.charAt(i)))

digit_count++;

if(Character.isLetter(temp_str.charAt(i))).

alphabet_count++;

}

token=new StringTokenizer(temp_str," "); Sample input file: inputfile.txt

while(token.hasMoreTokens())

{

word_count++;

String s=token.nextToken();

char_count+=s.length();

}

}

System.out.println("Character Count : "+char_count);

System.out.println("Word Count : "+word_count);

System.out.println("Line Count : "+line_count);

System.out.println("Aplphabet Count : "+alphabet_count);

System.out.println("Digit Count : "+digit_count);

System.out.println("White Space Count : "+wspace_count);

br.close();

}

}

Output

Enter filename : inputfile.txt

Character Count: 36

Word Count : 10

Line Count: 4

Alphabet Count: 32

Digit Count: 3

White Space Count: 6

Ex. 4.3.7 Create an IN file in Java to store the details of 100 students using Student class. Read the details from IN file, Convert all the letters of IN file to lowercase letters and write it to OUT file.

Sol.:

Step 1: Create a Student class in a separate Java file

import java.io.Serializable;

public class Student implements Serializable {

//default serialVersion id

private static final long serialVersionUID = 1L;

private String first_name;

private String last_name;

private int age;

public Student(String fname, String Iname, int age){

this.first_name = fname;

this.last_name = Iname;

this.age = age;

}

public void setFirstName(String fname) {

this.first_name = fname;

}

public String getFirstName() {

return this.first_name;

}

public void setLastName(String Iname) {

this.first_name = Iname;

}

public String getLastName() {

return this.last_name;

}

public void setAge(int age) {

this.age age;

}

public int getAge() {

return this.age;

}

@Override

public String toString() {

return new StringBuffer("\t").append(this.first_name)

.append("\t").append(this.last_name).append("\t").append(this.age).toString();

}

}

Step 2: Create another java file for performing file handling operations.

StudentDemo.java

import java.io.FileInputStream; import java.io.FileOutputStream;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.util.Scanner;

public class Student Demo

{

private static final String filepath="D:\\IN.txt";

public static void main(String args[])

{

StudentDemo objectIO = new StudentDemo();

try

{

FileOutputStream fileOut = new FileOutputStream("D:\\IN.txt");

ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);

for(int i=0;i<100;i++)

{

Scanner sc = new Scanner(System.in);

System.out.println("Enter first name of the student: ");

String fname= sc.next();

System.out.println("Enter last name of the student: ");

String Iname= sc.next();

System.out.println("Enter Age of the student: ");

int age=sc.nextInt();

Student student = new Student (fname,lname, age);

objectOut.writeObject((Object)student);

}

System.out.println(" The File is created Successfully ");

objectOut.close();

}

catch (Exception ex)

{

ex.printStackTrace();

}

//Read object from IN.txt and write to OUT.txt

Student st;

try

{

FileInputStream fileIn = new FileInputStream("D:\\IN.txt");

ObjectInputStream objectIn = new ObjectInputStream(fileIn);

FileOutputStream fileOut = new FileOutputStream("D:\\OUT.txt");

ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);

Object obj;

for(int i=0;i<100;i++)

{

obj = objectIn.readObject();//reading object

st=(Student)obj; //converting it to Student type

String fn= st.getFirstName().toLowerCase();

String In= st.getLastName().toLowerCase();

Student student = new Student (fn,in,st.getAge());

objectOut.writeObject((Object)student); //writing the modified object

}

System.out.println("The File is copied Successfully"); .

objectIn.close();

objectOut.close();

}

catch (Exception ex)

{

ex.printStackTrace();

}

//Read object from OUT.txt

try

{

FileInputStream fileIn = new FileInputStream("D:\\OUT.txt");

ObjectInputStream objectIn = new ObjectInputStream(fileIn);

Object obj;

System.out.println(" FirstName LastName Age");

for(int i=0;i<100;i++)

{

Obj = objectIn.readObject();

System.out.println((Student)obj);

}

objectIn.close();

}

catch (Exception ex)

{

ex.printStackTrace();

}

}

}

Review Question

1. Explain in detail about the following with sample program:

i) Reading from a file ii) Writing in a file.

Object Oriented Programming: Unit IV: I/O, Generics, String Handling : Tag: : Methods, Purpose with Example Java Programs - Reading and Writing Files