/home/caleb/ASDV-Java/Semester 2/Assignments/lab7_CalebFontenot/src/main/java/com/calebfontenot/lab7_calebfontenot/removeAllOccurances.java
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.calebfontenot.lab7_calebfontenot;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

/**
 *
 * @author caleb
 */
public class removeAllOccurances {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a path to a file: ");
        String sourcePath = input.nextLine();
        System.out.print("Replace what with what? (ex. If you want to replace John with Mary, type: \'John Mary\'): ");
        String source = input.next();
        String target = input.next();
        input.nextLine();  // Consume newline left-over
        System.out.print("Enter the output file path: ");
        String destinationPath = input.nextLine();

        File sourceFile = new File(sourcePath);
        File destinationFile = new File(destinationPath);
        String[] fileContents = new String[(int) countLines(sourceFile)];
        try (Scanner sourceScanner = new Scanner(sourceFile)) {
            for (int i = 0; i < countLines(sourceFile); ++i) {
                fileContents[i] = sourceScanner.nextLine();
            }
        }
        for (int i = 0; i < fileContents.length; ++i) {
            fileContents[i] = fileContents[i].replace(source, target);
            System.out.println(fileContents[i]);
        }
        // Write contents to new file
        try (PrintWriter fw = new PrintWriter(destinationFile);) {
            for (int i = 0; i < fileContents.length; ++i) {
                fw.println(fileContents[i]);
            }
        }
    }

    public static int countLines(File sourceFile) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(sourceFile));
        int lines = 0;
        while (reader.readLine() != null) {
            lines++;
        }
        reader.close();
        return lines;
    }
}