Page 371 - Cs_withBlue_J_C11_Flipbook
P. 371
Program 5 Define a class called Flowers to perform read and write operations on a text file “Flower.txt”.
The detail of the class is given as follows:
Data Members
String fname : To store names of flowers
Member Methods
void createFile() : Accepts names of flowers and stores them in a text file “Flower.txt”
void readFile() : Reads text file “Flower.txt” and prints names of those flowers
that start with vowels
static void main() : Creates object and executes other methods
1 import java.io.*;
2 import java.util.*;
3 class Flowers
4 {
5 String fname; // data member
6 void createFile() throws IOException
7 {
8 // declaring the classes required to create file
9 // parameter true opens file in append mode
10 FileWriter fw=new FileWriter("Flower.txt",true);
11 BufferedWriter bw=new BufferedWriter(fw);
12 PrintWriter pw=new PrintWriter(bw);
13 Scanner sc=new Scanner(System.in);
14 char ch='y';
15 while(ch=='y' || ch=='Y') // loop to store multiple records
16 {
17 System.out.println("Enter the name of the flower");
18 // entering data using Scanner class
19 fname=sc.next();
20 // writing data to buffer using specific write methods of data type
21 pw.println(fname);
22 System.out.print("Continue y/n");
23 ch=sc.next().charAt(0);
24 }
25 // closing the objects transfers data in buffer to file permanently
26 pw.close();
27 bw.close();
369
Basic Input/Output and Data File Handling 369

