In: Computer Science
Write a java code to demonstrate the File IO. Your code should get the following information from the user.
• Get a file name fname for output • Get number of data (numbers) (N) you want to process from the user
• Get N numbers from the users through keyboard and store them in an array
• Get M (How many numbers to read from file)
• (Or)You are free to use same N for M (use N for both purposes) You have to define two methods:
1) To write the numbers from the array into the file fname
2) To read numbers from the file fname, store them in an array, and compute average of the numbers.
The method should display the numbers from the array and the average value.
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public class FileProcessing {
public static void main(String[] args) throws
Exception {
Scanner sc = new
Scanner(System.in);
System.out.println("Enter filename:
");
String fname = sc.next();
//reading n
System.out.println("Enter numer of
elements ");
int n = sc.nextInt();
int arr[] = new int[n];
//reading numbers into array
System.out.println("Enter " + n + "
elements : ");
for (int i = 0; i < n;
i++)
arr[i] =
sc.nextInt();
//calling method to write into
file
writeIntoFile(arr, fname);
//calling method to read from
file
readNumbersAndDisplay(fname,
n);
}
//reading from file
private static void readNumbersAndDisplay(String name,
int aN) throws Exception {
Scanner sc = new Scanner(new
File(name));
int i = 0;
int arr[] = new int[aN];
double sum = 0;
while (sc.hasNext()) {
arr[i] =
sc.nextInt();
sum +=
arr[i++];
}
double avg = sum / aN;
System.out.println("Sum : " +
sum);
System.out.println("Average: " +
avg);
}
private static void writeIntoFile(int[] arr, String
name) throws Exception {
PrintWriter pw = new
PrintWriter(new File(name));
for (int i : arr)
pw.println(i);
pw.close();
}
}
Note : If you like my answer please rate and help me it is very Imp for me