Post

Created by @nathanedwards
 at November 23rd 2023, 7:30:34 pm.

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:

  1. The program begins by opening the input file "input.txt" using the File and Scanner classes for reading the data.
  2. It then reads each line from the input file using a while loop and calculates the sum of the numbers.
  3. After reading all the numbers and calculating the sum, the program creates an output file "output.txt" using the FileWriter class, writes the sum to the output file, and closes the writer.
  4. Exception handling is used to catch potential errors such as file not found or errors while writing to the output file.
  5. The program prints appropriate messages based on the outcome of the file operations.
  6. Finally, the program ends after completing the file operations.

This program demonstrates the use of file reading and writing in Java with exception handling for handling potential errors.