-2

I have a bunch of files with characters that I want to replace in them. For example, if a file is called "test!file.txt" the system should print that, then change the file's name to "test_file.txt". I don't want to rename the whole file just the "!". And there are lots of files so renaming just a single won't work. I want the program to change all of the "!" in all of the file names to "_". Here is the code that I have but it only prints the file name and doesn't replace it.

import java.io.*;

class Files {
    public static void main(String[] args) {
        File folder = new File(".");
        String replaceThis = "!";

        for (File file : folder.listFiles()) {
            if (file.getName().contains(replaceThis)) {
                System.out.println(file.getName());
                file.getName().replace(replaceThis, "_");

            }
        }
    }
}
Kayaan
  • 7
  • 2

2 Answers2

-1

Take a look at the renameTo() method from java.io.File.

Also since Strings are designed as immutables, you aren't actually changing any file names in your code. String::replace() returns a new String with the replacements made, it doesn't change the String on which it's called.

Deconimus
  • 85
  • 5
-1

Modify this part of your code:

if (file.getName().contains(replaceThis)) {
            System.out.println(file.getName());
            file.getName().replace(replaceThis, "_");

        }

to

name = file.getName();
newFile = //your logic for new file name
File file2 = new File(newFile);
file.renameTo(file2);