Text file gradetxt contains 10 students grade Each line with
Text file “grade.txt” contains 10 students grade. Each line with one grade.
–Read all grades from the file “grade.txt” and write them as integers into a binary file (binaryGrade.dat).
–Read grades from the binary file “binaryGrade.dat” and compute and display the average grade.
To be done in Java
Solution
Please follow the code and comments for descritpion :
CODE :
import java.io.*;
public class TextToBinary { // class to run the code
public static void main(String[] args) throws IOException { // driver method
String line; // local varaibles
FileOutputStream fstream = new FileOutputStream(\"binaryGrade.dat\"); // stream data for the binary file
DataOutputStream os = new DataOutputStream(fstream); // data stream
BufferedReader br = new BufferedReader(new FileReader(new File(\"grade.txt\"))); // reader file to get the data from the text file
System.out.println(\"Writing the data to the Binary File....\"); // prompt for the user
while ((line = br.readLine()) != null) { // read the data till the end of the file
int grades = 0; // local varaibles
line = line.substring(line.indexOf(\"=\") + 1, line.length()); // get the grades values
grades = Integer.parseInt(line.trim());
os.writeInt(grades); // write the data to the binary file
}
System.out.println(\"Completed Successfully Writing the Data to the Binary File.\"); // message to the user
br.close(); // close the files
os.close();
DataInputStream input = new DataInputStream(new BufferedInputStream(new FileInputStream(\"binaryGrade.dat\"))); // stream for the binary file
System.out.println(\"Reading the Data from the Binary File...\"); // message for the user
long total = 0; // required varaibles
double avgGrade = 0;
int count = 0;
while (input.available() > 0) { // check for the user data in the file
count++; // increment the count value
total += input.readInt(); // add up the values
}
avgGrade = total / count; // calculate the averages
System.out.println(\"Calculating the Average Grade of the Data...\"); // message to the user
System.out.println(\"The Average Grade is : \" + avgGrade); // print the data to console
input.close(); // close the stream
}
}
OUTPUT :
Writing the data to the Binary File....
Completed Successfully Writing the Data to the Binary File.
Reading the Data from the Binary File...
Calculating the Average Grade of the Data...
The Average Grade is : 5.0
grade.txt :
A+ = 10
A = 9
B+ = 8
B = 7
C+ = 6
C = 5
D+ = 4
D = 3
E = 2
F = 1
Hope this is helpful.

