String Tokenizer:
Java.util.Tokenizer Class provides the facility to extract token form a token string. Token is sequence of character that is separated by a delimiter by a other tokens. While space as default delimiter.
public StringTokenizer(String str, String delim)
public StringTokenizer(String str)
public boolean hasMoreToken()
public String nextToken()
String str=”It is a tokend string.”;
StringTokenizer st=new StringTokenizer(str);
While(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
Real Example of StringTokenizer:
public class Emp implements Serializable{
String name;
int marks;
String address;
public Emp(){
}
public Emp(String name,int marks, String address)
{
this.name=name;
this.marks=marks;
this.address=address;
}
@Override
public String toString() {
return name+"\t"+marks+"\t"+address;
}
public void display(){
System.out.println("Name "+name);
System.out.println("Marks "+marks);
System.out.println("Address "+address);
}
}
public class RecordSaver {
public static void main(String as[])throws Exception{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(new FileOutputStream("d:/Emp.txt"));
Emp e;
while(true){
System.out.println("Enter Name:");
String name=b.readLine();
System.out.println("Enter Marks:");
int marks=Integer.parseInt(b.readLine());
System.out.println("Enter Address:");
String address=b.readLine();
e=new Emp(name,marks,address);
out.println(e.toString());
System.out.println("Want to continue...(yes/no)");
String ans=b.readLine();
if(ans.equalsIgnoreCase("no"))
break;
}
out.close();
out.flush();
}
public class RecordReader {
public static void main(String as[])throws Exception{
BufferedReader b=new BufferedReader(new FileReader("d:/Emp.txt"));
System.out.println("Following records are read from file::");
Emp e;
while(true){
String rec=b.readLine();
if(rec==null)
break;
StringTokenizer st=new StringTokenizer(rec,"\t");
String name=st.nextToken();
int marks=Integer.parseInt(st.nextToken());
String address=st.nextToken();
e=new Emp(name,marks,address);
e.display();
}
}
}
No comments:
Post a Comment