• Post Reply Bookmark Topic Watch Topic
  • New Topic

writing to a file

 
Rashi Gulati
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
I have written a program which takes the number from the user then calculate the factorial on that number and then create the file like 1.txt,2.txt and so on then write the factorial to this file but my problem is that iam able to create the file but iam not able to write it to the file iam enclosing the code as well please have alook.

import java.io.*;
import java.lang.*;

public class CalculateFactorialFile
{
String fileName,newfileName;
String ext =".txt";
int number,factorial,count;
File file;
InputStreamReader dataInput;
BufferedReader buffer;
FileWriter fileOutput;


int input()
{
int count=1;
int flag=0;
String s;
try
{
dataInput= new InputStreamReader(System.in);
buffer = new BufferedReader(dataInput);
System.out.print("Enter the number :");
s=buffer.readLine();
number=Integer.parseInt(s);
System.out.println("Number is :"+number);
}
catch(IOException e)
{
System.out.println("Exception"+e);
}
return number;
}

int calculateFactorial(int number)
{
factorial=1;
for(count=1;count<=number;count++)
{
factorial=count*factorial;
}
System.out.print("Factorial is :"+factorial);
return factorial;
}

void output(int factorial)
{
int flag=0;
boolean result;
int count=1;

System.out.println("Fact :"+factorial);
while(flag==0)
{

fileName= count+ext;
file = new File(fileName);

try
{
result=file.createNewFile();
if(result==false)
{
count++;
}
else
{
flag=1;
}


}
catch(FileNotFoundException f)
{
System.out.println("FileNotFound"+f);
}
catch(IOException i)
{
System.out.println("IOexception"+i);
}

}

try
{
if(fileOutput== null)
{
fileOutput = new FileWriter(file);
fileOutput.write(factorial);
}
}
catch(IOException eo)
{
System.out.println("IOException"+eo);
}
catch(Exception r)
{
System.out.println("Exception"+r);
}
}

public static void main(String args[])
{
CalculateFactorialFile fac = new CalculateFactorialFile();
int actualNumber,fact;
System.out.println("Taking input");
actualNumber=fac.input();
System.out.println("Calculating factorial");
fact=fac.calculateFactorial(actualNumber);
System.out.println("Writing output");
fac.output(fact);
}
}

Regards
Rashi
 
Joe Ess
Bartender
Posts: 9361
11
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have to invoke flush() on your output writer to make sure that the data is written to disk before your program terminates. Invoking close() when you are done with an output file is a Good Thing as well.
 
Rashi Gulati
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks alot Joe i have tried that and now it is working fine, that was really bugging me for so long.
Thanks alot
Regards
Rashi
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!