ericrk00 ericrk00 - 3 months ago 10
Java Question

Word replacement from a folder with multiple files using java

I have a java program that will do a word replacement for a single file by providing a path. I want to change this java program so it can be excused in a folder with many files. Once it make the changes it writes back to the file. I'm stuck on how to do this. I know I need a loop to go over the file.
Question: What java api should I be using for reading from the folders
Here is my code:

import java.io.* ;
public class Replace{
public static void main(String[] args) {
File file = new File("My_text.txt");


try
{
BufferedReader reader = new BufferedReader(new FileReader(file));

String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\r\n";
}
reader.close();

String replacedtext = oldtext.replaceAll("<eol> ", "");
replacedtext = replacedtext.replaceAll("<eos> ", "");
replacedtext = replacedtext.replaceAll(" \\.", ".");
replacedtext = replacedtext.replaceAll(" \\,", ",");
//replacedtext = replacedtext.replaceAll(" ", "");
replacedtext = replacedtext.replaceAll(" \\'s", "'s");

FileWriter writer = new FileWriter("My_text.txt");
writer.write(replacedtext);


writer.close();

}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}

Answer

This will do the trick. You can get all files with method listFiles() which you can call on File from java.io.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Replace {
    public static void main(String[] args) {
        File folder = new File("C:/PathToYourFolder");
        File[] listOfFiles = folder.listFiles();
        for(File file : listOfFiles) {
            replaceText(file);
        }
    }

    public static void replaceText(File file) {

        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));

            String line = "", oldtext = "";
            while ((line = reader.readLine()) != null) {
                oldtext += line + "\r\n";
            }
            reader.close();

            String replacedtext = oldtext.replaceAll("<eol> ", "");
            replacedtext = replacedtext.replaceAll("<eos> ", "");
            replacedtext = replacedtext.replaceAll(" \\.", ".");
            replacedtext = replacedtext.replaceAll(" \\,", ",");
            // replacedtext = replacedtext.replaceAll(" ", "");
            replacedtext = replacedtext.replaceAll(" \\'s", "'s");

            FileWriter writer = new FileWriter(file);
            writer.write(replacedtext);

            writer.close();

        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}