Question 1:
You are working on a Java program that reads data from a file and processes it. You have been provided with a file named "input.txt" that contains a list of numbers, one number per line. You need to read the numbers from this file, calculate the sum, and write the result to an output file named "output.txt". You should use exception handling to handle any potential file-related errors.
Write a Java program that accomplishes this task.
Answer:
import java.io.*;
import java.util.Scanner;
public class FileProcessing {
public static void main(String[] args) {
try {
// Open the input file
File inputFile = new File("input.txt");
Scanner scanner = new Scanner(inputFile);
int sum = 0;
// Read the numbers from the file and calculate the sum
while (scanner.hasNextLine()) {
int number = Integer.parseInt(scanner.nextLine());
sum += number;
}
scanner.close();
// Write the sum to the output file
File outputFile = new File("output.txt");
FileWriter writer = new FileWriter(outputFile);
writer.write("The sum of the numbers is: " + sum);
writer.close();
System.out.println("Sum successfully written to output.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("An error occurred while writing to the file: " + e.getMessage());
}
}
}
Explanation:
This program demonstrates the use of file reading and writing in Java with exception handling for handling potential errors.