Intro to Java - INTU
Question
I need to understand… how could I use the writing of files to save previous calculations?
Up until now, every program I wrote in Java didn’t use any files other than Main.java. Since user inputs and calculations aren’t saved anywhere, the data is forgotten and not usable in future runs. I want to learn how to write to a file to save data because it provides me with more options in future runs. An example of this would be if I saved the progress of a user to a file and used it to continue off where they left off.
Explanation
Creating the File
Before writing anything to a file, it needs to exist and be accessible to the program. To work with files, the File class must be imported. This gives access to the method required to create a new file. The IOException class should be imported too so that any errors can be displayed. Then, a try and catch block is used in case there are any errors. The program will try to create a new object, and then run an if statement to check whether the object could be created. If the file was created, the system will output a message to confirm that the file was created, else it would output that the file already existed. The catch block will run if for some reason it wasn’t able to create a file.
Writing to a File
To write to the now created file, you need to import the FileWriter class. In another try and catch block, the write() method can be used to write to a file. It is followed by the close() method to close the file. Any errors can be displayed as a system output. A problem with the current code is that it will overwrite any previously written data. To append new data to the file, true is added to the FileWriter method. Then any new data written to the file will be added to the end of the the existing. To write to a new line, \n can be used when writing strings.
Sources:
https://www.w3schools.com/java/java_files_create.asp
https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html
Example Code
import java.io.File; //file class
import java.io.IOException; //handles errors
import java.io.FileWriter; //file writing
import java.util.Scanner; //to read files
class Main {
public static void main(String[] args) {
//creating save file if it doesn't exist
try
{
File myResults = new File("savedresults.txt"); //creates new object
if (myResults.createNewFile()) //tries to create file
{
System.out.println("Created save file: " + myResults.getName());
}
else//runs if file wasn't able to create new file
{
System.out.println("Save file already exists");
}
}
catch (IOException e)//runs if errors occur
{
System.out.println("An error occured ):");
e.printStackTrace();
}
try
{
FileWriter myWriter = new FileWriter("savedresults.txt", true);//appends instead of overwrite
myWriter.write("\nTest result");//saves to next line
myWriter.close();//closes file
System.out.println("Successfully saved result to file.");
}
catch (IOException e)//runs if errors occur
{
System.out.println("An error occured ):");
e.printStackTrace();
}
}
}
Quadratic Formula Calculator
I added the ability to create and write to a file to my quadratic formula calculator. It will now run calculations and save them to the savedresults.txt file. With the addition, I can see what was previously calculated in earlier runs.
import java.io.File; //file class
import java.io.IOException; //handles errors
import java.io.FileWriter; //file writing
import java.util.Scanner; //to read files
import java.io.FileNotFoundException; //handles errors
import javax.swing.JOptionPane; //fancy GUI
class Main {
public static void main(String[] args) {
//variables
double b;
double a;
double c;
double x1;
double x2;
int repeat = 0;
//creating save file if it doesn't exist
try
{
File myResults = new File("savedresults.txt");
if (myResults.createNewFile())
{
System.out.println("Created save file: " + myResults.getName());
}
else
{
System.out.println("Save file already exists");
}
}
catch (IOException e)
{
System.out.println("An error occured ):");
e.printStackTrace();
}
try
{
FileWriter myWriter = new FileWriter("savedresults.txt", true);//appends instead of overwrite
myWriter.write("\nNew Session");//saves to next line
myWriter.close();
System.out.println("Successfully saved to file.");
}
catch (IOException e)
{
System.out.println("An error occured ):");
e.printStackTrace();
}
//explain what calculator does
JOptionPane.showMessageDialog(null, "Quadratic Formula", "Calculator", JOptionPane.INFORMATION_MESSAGE);
//loops as long as repeat is equal to 0
while (repeat == 0)
{
//ask user for values of a, b, and c
a = Double.parseDouble(JOptionPane.showInputDialog("What is the value of a?"));
b = Double.parseDouble(JOptionPane.showInputDialog("What is the value of b?"));
c = Double.parseDouble(JOptionPane.showInputDialog("What is the value of c?"));
//if the result is less than 0 it'll have no solution
if ((Math.pow(b,2) - 4 * a * c) < 0)
{
//tells user result
JOptionPane.showMessageDialog(null, "No solution", "Solution", JOptionPane.INFORMATION_MESSAGE);
try
{
FileWriter myWriter = new FileWriter("savedresults.txt", true);//appends instead of overwrite
myWriter.write("\nNo solution: " + "a=" + a + " b=" + b + " c=" + c);//saves to next line
myWriter.close();
System.out.println("Successfully saved result to file.");
}
catch (IOException e)
{
System.out.println("An error occured ):");
e.printStackTrace();
}
//asks user if they want to repeat
repeat = JOptionPane.showConfirmDialog(null,"Repeat?","Repetition", JOptionPane.YES_NO_OPTION);
//if they select anything but "yes", program will break from loops
if (repeat != 0)
{
break;
}
}
//else if the result is 0 it'll have one solution
else if ((Math.pow(b,2) - 4 * a * c) == 0)
{
//rounds answer to four decimals
x1 = (Math.round((-b+Math.sqrt(Math.pow(b,2)-4*a*c))/(2*a)*10000.0)/10000.0);
//tells user result
JOptionPane.showMessageDialog(null, "One solution\n" + x1, "Solution", JOptionPane.INFORMATION_MESSAGE);
try
{
FileWriter myWriter = new FileWriter("savedresults.txt", true);//appends instead of overwrite
myWriter.write("\nOne solution: " + "a=" + a + " b=" + b + " c=" + c + " x=" + x1);//saves to next line
myWriter.close();
System.out.println("Successfully saved result to file.");
}
catch (IOException e)
{
System.out.println("An error occured ):");
e.printStackTrace();
}
//asks user if they want to repeat
repeat = JOptionPane.showConfirmDialog(null,"Repeat?","Repetition", JOptionPane.YES_NO_OPTION);
//if they select anything but "yes", program will break from loops
if (repeat != 0)
{
break;
}
}
//else will run for two solutions
else
{
//rounds answer to four decimals
x1 = (Math.round((-b+Math.sqrt(Math.pow(b,2)-4*a*c))/(2*a)*10000.0)/10000.0);
x2 = (Math.round((-b-Math.sqrt(Math.pow(b,2)-4*a*c))/(2*a)*10000.0)/10000.0);
//tells user result
JOptionPane.showMessageDialog(null, "Two solutions\n" + x1 + "\n" + x2, "Solution", JOptionPane.INFORMATION_MESSAGE);
try
{
FileWriter myWriter = new FileWriter("savedresults.txt", true);//appends instead of overwrite
myWriter.write("\nTwo solutions: " + "a=" + a + " b=" + b + " c=" + c + " x=" + x1 + " x=" + x2);//saves to next line
myWriter.close();
System.out.println("Successfully saved result to file.");
}
catch (IOException e)
{
System.out.println("An error occured ):");
e.printStackTrace();
}
//asks user if they want to repeat
repeat = JOptionPane.showConfirmDialog(null,"Repeat?","Repetition", JOptionPane.YES_NO_OPTION);
//if they select anything but "yes", program will break from loops
if (repeat != 0)
{
break;
}
}
}
//program exits with code 0
System.exit(0);
}
}