Post

Created by @nathanedwards
 at November 2nd 2023, 6:16:45 pm.

AP Computer Science Exam Question

Write a Java program that reads a text file named "input.txt" and writes the content of the file to a new file named "output.txt". The program should also count the number of lines and characters in the input file and print out the counts.

Step-by-step solution

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class FileReadWrite {
    public static void main(String[] args) {
        // Step 1: Create file objects for input and output files
        File inputFile = new File("input.txt");
        File outputFile = new File("output.txt");
        
        // Step 2: Initialize line and character counters
        int lineCount = 0;
        int charCount = 0;
        
        try {
            // Step 3: Create a Scanner object to read from the input file
            Scanner scanner = new Scanner(inputFile);
            
            // Step 4: Create a FileWriter object to write to the output file
            FileWriter writer = new FileWriter(outputFile);

            // Step 5: Read input file line by line and write to output file
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                writer.write(line);
                writer.write("\n"); // Add newline character for each line
                
                lineCount++;
                charCount += line.length();
            }
            
            // Step 6: Close the scanner and writer objects
            scanner.close();
            writer.close();
            
            // Step 7: Print the line and character counts
            System.out.println("Number of lines: " + lineCount);
            System.out.println("Number of characters: " + charCount);
            
        } catch (FileNotFoundException e) {
            System.out.println("Input file not found!");
        } catch (IOException e) {
            System.out.println("Error writing to output file!");
        }
    }
}

Explanation

  1. We start by creating File objects for the input and output files. In this solution, the input file is named "input.txt" and the output file is named "output.txt".

  2. We initialize two variables lineCount and charCount to keep track of the number of lines and characters in the input file.

  3. We create a Scanner object to read from the input file. We use a try-catch block to handle the FileNotFoundException that may occur if the input file is not found.

  4. We create a FileWriter object to write to the output file. We use a try-catch block to handle the IOException that may occur if there is an error writing to the output file.

  5. We read the input file line by line using a while loop. For each line, we write it to the output file using the write method of the FileWriter object. We also increment the line count by 1 and add the length of the line to the character count.

  6. After reading all the lines, we close the Scanner and FileWriter objects to release system resources.

  7. Finally, we print the line and character counts to the console.

Make sure to have the input.txt file in the same directory as the Java source file before running the program. After running the program, the output.txt file will be created with the same content as input.txt, and the line and character counts will be printed on the console.