// This program creates a file, adds data to the file, displays the file,
// appends more data to the file, displays the file, and then deletes the file.
// It will not run if the file already exists.
//
// References:
// https://www.mathsisfun.com/temperature-conversion.html
// https://en.wikibooks.org/wiki/Java_Programming
import java.util.*;
class Main {
public static void main(String[] args) {
String FILENAME = "~file.txt";
if(fileExists(FILENAME)) {
System.out.println("File already exists.\n");
} else {
createFile(FILENAME);
readFile(FILENAME);
appendFile(FILENAME);
readFile(FILENAME);
deleteFile(FILENAME);
}
}
private static double calculateFahrenheit(double celsius) {
double fahrenheit;
fahrenheit = celsius * 9 / 5 + 32;
return fahrenheit;
}
private static void createFile(String filename) {
try {
java.io.File file = new java.io.File(filename);
java.io.BufferedWriter writer =
new java.io.BufferedWriter(new java.io.FileWriter(file));
double celsius;
double fahrenheit;
writer.write("Celsius,Fahrenheit\n");
for(celsius = 0; celsius <= 50; celsius++) {
fahrenheit = calculateFahrenheit(celsius);
writer.write(celsius + "," + fahrenheit + "\n");
}
writer.close();
} catch(Exception exception) {
System.out.println("Error creating " + filename);
exception.printStackTrace();
}
}
private static void readFile(String filename) {
try {
java.io.File file = new java.io.File(filename);
java.io.BufferedReader reader =
new java.io.BufferedReader(new java.io.FileReader(file));
String line;
while(true) {
line = reader.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
reader.close();
System.out.println("");
} catch(Exception exception) {
System.out.println("Error reading " + filename);
exception.printStackTrace();
}
}
private static void appendFile(String filename)
{
try {
java.io.File file = new java.io.File(filename);
java.io.BufferedWriter writer =
new java.io.BufferedWriter(new java.io.FileWriter(file, true));
double celsius;
double fahrenheit;
for(celsius = 51; celsius <= 100; celsius++) {
fahrenheit = calculateFahrenheit(celsius);
writer.write(celsius + "," + fahrenheit + "\n");
}
writer.close();
} catch(Exception exception) {
System.out.println("Error appending to " + filename);
exception.printStackTrace();
}
}
private static void deleteFile(String filename) {
java.io.File file;
try {
file = new java.io.File(filename);
file.delete();
} catch(Exception exception) {
System.out.println("Error deleting " + filename);
exception.printStackTrace();
}
}
private static boolean fileExists(String filename) {
java.io.File file;
file = new java.io.File(filename);
return file.exists();
}
}