Qwerty Qwerty - 1 year ago 59
Java Question

Referring files in a folder with similar name,editing , and then renaming them individually

I have a set of files like "f-1.txt" , "f-2.txt", ..... , "f-30.txt", "g-1.txt" , "g-2.txt", ..... , "g-23.txt","h-1.txt" , "h-2.txt", ..... , "h-35.txt"..etc in a folder.I want to add a few things to each of them and rename them like "f-1new.txt" , "g-2new.txt". How can I refer them in java preferably using wildcard and rename them suitably?

For a particlar file, I use BufferedReader to read its contents and Printwriter to write modified contents to a new file name.. But how can I read contents from all files, (iteratively) if the names varies too much(yet maintain order) like the ones described above?

I have refrred to this but it didnt help me with how to get the file names of each file in the array(the first answer in the post)..

Answer Source

Here is one solution.

public class Main {

public static void main(String[] args) throws FileNotFoundException, IOException {

    String PATH_2_FOLDER = "path_2_folder";

    //listing all files in the desired folder
    File myDirectory = new File(PATH_2_FOLDER);
    File[] allFiles = myDirectory.listFiles();


    for (int l = 0; l < allFiles.length; l++) {

        if (allFiles[l].getName().endsWith(".txt")) {

            //read the input file
            String thisPathIn = PATH_2_FOLDER+allFiles[l].getName();
            BufferedReader thisBR = new BufferedReader(new FileReader(thisPathIn));

            //create the output file
            String newName = allFiles[l].getName().replace(".txt", "").concat(".new.txt");
            String thisPathOut = PATH_2_FOLDER+newName;
            BufferedWriter thisBW = new BufferedWriter(new FileWriter(thisPathOut));

            //read the contents of the inputfile
            String s = "";
            while((s = thisBR.readLine()) != null){

            //process the content
            //create new content






Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download