Search code examples
javafilewriterreplaceall

File read, changed but how to write out?


Ok, forgive my beginner-ness and please tell me how I can output my text from "before.txt" into a fresh new file called "after". Obviously I have altered the text along the way to make it lower-case and eliminate non alphabetic characters.

import java.io.*;

public class TextReader {

    public void openFile() throws IOException {
        try {
            // Read in the file
            BufferedReader br = new BufferedReader(
                    new FileReader(
                    new File("before.txt")));

            String currentLine = br.readLine();

            currentLine = currentLine.toLowerCase();
            currentLine = currentLine.replaceAll("[A-Z]", "");
            br.close(); // Close br to prevent resource leak
        }
        // Exception if the file is not in the path specified
        catch (Exception e) {
            System.out.println("Error: File not found");
        }
    }

    public void writeFile() throws IOException {
        BufferedWriter output  = new BufferedWriter(new FileWriter("/WS3Ex3/after.txt"));    
        output.write("before.txt");
        output.close();
    }
}

Solution

  • What about this

    public void openFile() throws IOException {
        try {
            // Read in the file
            BufferedReader br = new BufferedReader(
                    new FileReader(
                    new File("before.txt")));
    
            String currentLine = br.readLine();
    
            currentLine = currentLine.toLowerCase();
            currentLine = currentLine.replaceAll("[A-Z]", "");
            br.close(); // Close br to prevent resource leak
            writeFile(currentLine);
    
        }
        // Exception if the file is not in the path specified
        catch (Exception e) {
            System.out.println("Error: File not found");
        }
    }
    
    public void writeFile(String text) throws IOException {
        BufferedWriter output  = new BufferedWriter(new FileWriter("/WS3Ex3/after.txt"));
        output.write(text);
        output.close();
    }
    }
    

    Let me guess, is this a school assignment?