-1

I have a python program that can remove strings from files name but I am looking for help using java.

something similar to this

import glob,os
from tkinter import filedialog
import re

#in_path = filedialog.askdirectory() # if want to ask for directory

os.chdir(os.path.join("G:\\"))  #change to os.chdir(os.path.join(in_path)) to used selected dir
for files in glob.glob("*.mp4"):  #get mp4 files
    filename = os.path.splitext(files)
    ext=filename[-1]
    thefile = filename[0]
    if "v" in thefile:  #if there is version, check where the letter "v" is
        ind = thefile.index("v")
        change = thefile[:ind].replace(".","").replace("_","")+thefile [ind:].replace("_","")+ext
    else:
        change = thefile.replace(".","")+ext
    os.rename(files,change)
Tpd
  • 25
  • 5

1 Answers1

0
import java.io.*;

public class Renamer {

    public void renameFiles(String dir, String search) throws IOException{
        File directory = new File(dir);
        File[] directoryListing = directory.listFiles();
        if (directoryListing != null) {
            for (File child : directoryListing) {
                if(child.getName().contains(search)){
                    int start = child.getName().indexOf(search);
                    String newFileName = child.getName().substring(0, start);
                    File newFile = new File(newFileName);
                    child.renameTo(newFile);
                }  
            }
        }
    }
}

Try this, some of what you want to do can be OS Specific as to the way in which the OS handles files, bit it should work. Basically what this does is searches for a string and renames the file to contain only what is before that string. And it does it for all files within the given directory.

I didn't add the functionality for only doing specific file extensions, but that wouldn't be hard to implement.

  • not sure how renameTo() behaves completely, so it might leave a bunch of blank files with the new names... – Eddie Fiorentine Nov 26 '16 at 03:54
  • I get to read and everthing but the newFileName is coming back blank Searching for: unt Printing Child Name untitled.3ds Printing Rename Printing Child Name untitled.stl Printing Rename – Tpd Nov 26 '16 at 21:11