/**
This program shows how to write (create) a txt file.
To create a txt file, we use mainly two calsses:
PrintWriter and FileWriter:
FileWriter TheFileToWrite = new FileWriter (NameOfFile);
PrintWriter TheOutputFile = new PrintWriter (TheFileToWrite);
Or, in one line:
PrintWriter TheOutputFile = new PrintWriter (new FileWriter (NameOfFile));
To write, we apply the method print or println to the object
TheOutputFile of the Java predefined class PrintWriter:
TheOutputFile.println(" ") ;
We use TheOutputFile.close(); to close the file.
*/
/*
In this example, we write the file FibonacciN.txt of
the first N+1 integers.
*/
import java.io.*;
public class WriteFiles {
static int Fibonacci (int n){
if (n <=1)
return n;
else
return Fibonacci (n-1) + Fibonacci (n-2);
}
static void FileFibonacci (int nbMax, String TheFile)throws IOException {
PrintWriter ThisFile = new PrintWriter ( new FileWriter(TheFile));
for (int k = 0; k<= nbMax; k++)
ThisFile.println ("Fibonacci(" + k + ")\t" + Fibonacci(k));
ThisFile.close();
System.out.println ("The file :" + TheFile + " is created.");
}
public static void main (String [] args) throws IOException {
if (args.length == 2){
int nbMax = Integer.parseInt(args[0]);
String TheFile = args[1];
FileFibonacci(nbMax, TheFile);
}
}
/*
Compile:
C:\Java> javac WrieFiles.java
Execute:
First argument = 10 , We will have then Fibonacci values of the
eleven first integers,
Second argument: Fibonacci10.txt : the file will be written as
Fibonacci10.txt.
C:\Java> java WriteFiles 10 Fibonacci10.txt
The file :Fibonacci10.txt is created.
We can open the file Fibonacci10.txt to see:
Fibonacci(0) 0
Fibonacci(1) 1
Fibonacci(2) 1
Fibonacci(3) 2
Fibonacci(4) 3
Fibonacci(5) 5
Fibonacci(6) 8
Fibonacci(7) 13
Fibonacci(8) 21
Fibonacci(9) 34
Fibonacci(10) 55
*/
/*Recall:
C:\Java> java Class Fisrt_arg Second_arg(file)
*/
PrintWriter TheOutputFile =
new PrintWriter (new FileWriter (NameOfFile));
|