Thursday, October 28, 2010

File Handling In Java

The following program is on file handling in java. Names of several persons are to be written in a text file in the format name-middlename-surname. In case there is no middle name, record is entered as name and surname. Records are displayed as Middle name, Name and SurName. If there is no middle name then 'XX' is displayed in middle name part.

import java.io.*;
import java.util.*;
class BlueJx
{
public static void main(String args[]) throws IOException
{
byte barr[];
StringTokenizer stk;
String name,mname,sname;
int pos;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
FileOutputStream fout;
FileInputStream fin;
fout=new FileOutputStream("record.txt",true);
String str;
/*2nd argument true means the values will be appended in the file*/

System.out.println("Enter the Name with middle Name and Surname");
str=br.readLine();
str="*"+str;
barr=str.getBytes();
fout.write(barr);
// for reading
fin=new FileInputStream("record.txt");
pos=fin.available();
barr=new byte[pos];
System.out.println("\nRecords as follows\n");
fin.read(barr);
str=new String(barr);
stk=new StringTokenizer(str,"*");
while(stk.hasMoreTokens())
{
str=stk.nextToken();
pos=str.lastIndexOf(" ");
sname=str.substring(pos).trim();
str=str.substring(0,pos).trim();
pos=str.lastIndexOf(" ");
if(pos!=-1)
{
mname=str.substring(pos).trim();
name=str.substring(0,pos).trim();
}
else
{
mname="XX";
name=str;
}
System.out.println(mname + " "+ name+" "+ sname);
}
}
}

Related Post:  BlueJ Programs on String/Sentence

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner