Write a program using the following question Text file grade
Write a program using the following question:
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.
Using standard java code complete and write the program for this question.
Solution
grade.txt (We have to save this file in D Drive.Then the Path of the file pointing to it is D://grade.txt)
56
78
98
87
76
66
77
88
92
84
_____________________
binaryGrade.dat (We can find this fiule under the D Drive.As we specified the path of file as D://binaryGrade.dat)
111000
1001110
1100010
1010111
1001100
1000010
1001101
1011000
1011100
1010100
_____________________
ReadFile.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) throws IOException {
//Calling the methods
readDecimal();
readBinary();
}
/* This method will read the decimal numbers from the file and
* convert each number to decimal format and write it into another file
*/
private static void readDecimal() throws IOException {
// Create FileWriter Reference
FileWriter fileWriter = null;
// Creating the Scanner class reference.
Scanner scanner = null;
BufferedWriter bw = null;
try {
// Creating Scanner object by passing the file Object as input
scanner = new Scanner(new File(\"D:\\\\grade.txt\"));
// Creating an output file
File output = new File(\"D:\\\\binaryGrade.dat\");
fileWriter = new FileWriter(output);
bw = new BufferedWriter(fileWriter);
// This while loop will write the data(Binary Numbers) to the file
while (scanner.hasNext()) {
/*
* Getting the each decimal number from the file and converting
* it into binary form and writing into another file
*/
bw.write(Integer.toBinaryString(scanner.nextInt()));
bw.write(\"\ \ \");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bw.close();
}
/* This method will read the binary numbers from the file,
* convert to decimal number and find average and display
*/
private static void readBinary() {
double sum = 0.0, average = 0.0;
int count = 0;
try {
Scanner scanner = new Scanner(new File(\"D:\\\\binaryGrade.dat\"));
while (scanner.hasNext()) {
//Calculating the sum of all decimal numbers
sum += Integer.parseInt(scanner.next(), 2);
//Counting how many numbers are there
count++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//calculating the average
average = sum / count;
//Displaying the average
System.out.println(\"Average :\" + average);
}
}
____________________
Output:
Average :80.2
_____Thank You


