(15 marks) Write a Java program to track how many times the program has been exe
ID: 3737628 • Letter: #
Question
(15 marks) Write a Java program to track how many times the program has been executed. You will store the number (integer)representing the count into a file (count.dat). If the count.dat doesn't exist (e.g., first time to run the program), store 1 in the newly created file. You will use binary IO (FilelnputStream FileOutputSteam) for your code. For this question, you will also need to declare the checked exceptions in the method's header to handle errors. Since the counter.dat file is a binary file (you cannot read it with your typical text editor(eg MS words), you can use your Hex viewer method program from the following question to open the file to examine the contents. If you are using notepad++, you can also d ownload the HexEditor plugin to enable the Hex view. Please submit your count.dat file as well as the java file for this questionExplanation / Answer
ExecutionTracker.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;
public class ExecutionTracker {
public static void main(String[] args) throws IOException {
File file = new File("count.dat");
int executionCount = 0;
if(file.exists()){
Scanner scan = new Scanner(new FileInputStream(file));
executionCount = Integer.parseInt(scan.next());
}
executionCount++;
PrintStream output = new PrintStream(new FileOutputStream(file));
output.print(""+executionCount);
output.flush();
output.close();
System.out.println("File has been created");
}
}
Output:
File has been created
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.