Write a Java program to track how many times the program has been executed. You
ID: 3735445 • Letter: W
Question
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 (FileInputStream / 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 download the HexEditor plugin to enable the Hex view. Please submit your count.dat file as well as the java file for this question
Explanation / Answer
CODE:
import java.io.File;
import java.io.RandomAccessFile;
import java.io.IOException;
public class Exercise_1
{
public static void main(String args[]) throws IOException
{
File file=new File(“Exercise_1.dat”);
try(RandomAccessFile raf=new RandomAccessFile(file,”rw”))
{
int count = (raf.length()!=0)? Raf.readInt()+1:1;
raf.seek(0);
raf.writeInt(count);
System.out.println(“Count is ”+count);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.