Write an application that writes the first 15 numbers of the Fibonacci series to a file .Write a second application that reads this data from a file and display it. For both application, specify, the name of the file as command-line argument.
source file name: fibfilewrite.java
import java.io.*;
class fibfilewrite
{
public static void main(String args[]) throws IOException
{
FileOutputStream f1=null;
int no=12;
int a=0,b=1,sum;
int n=1;
System.out.print(a+","+b);
f1=new FileOutputStream(args[0]);//command line parameter
DataOutputStream dos=new DataOutputStream(f1);
do
{
sum=a+b;
dos.writeInt(sum);
System.out.print(","+sum);
a=b;
b=sum;
n++;
}
while(n<=no);
System.out.println();
System.out.println("Fib series store in File "+args[0]);
dos.close();
f1.close();
}
}
output:
D:\JavaPrograms\IOFilePrograms>javac fibfilewrite.java
D:\JavaPrograms\IOFilePrograms>java fibfilewrite fibdata.txt
0,1,1,2,3,5,8,13,21,34,55,89,144,233
Fib series store in File fibdata.txt
source file name: Readfib.java
import java.io.*;
class Readfib
{
public static void main(String args[]) throws IOException
{
FileInputStream f2=null;
f2=new FileInputStream(args[0]);//command lline parameter
DataInputStream dos1=new DataInputStream(f2);
String s="";
while(dos1.read()!=-1)//file data reads till -1
{
s=s+dos1.read()+"";
}
String ss[]=s.split("0");
System.out.print("0,1");
for(int i=0;i<ss.length;i++)
System.out.println(ss[i]+",");
}
}
output:
D:\JavaPrograms\IOFilePrograms>javac Readfib.java
D:\JavaPrograms\IOFilePrograms>java Readfib fibdata.txt
0,1,
1,
2,
3,
5,
8,
13,
21,
34,
55,
89,
144,
233,
0 Comments
Post a Comment