2016-11-26 124 views
-1

我有一个python程序,可以从文件名中删除字符串,但我正在寻找使用java的帮助。如何使用java重命名文件

与此类似

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) 
+0

我们理解你,但你应该向我们提出一些Java代码,而不是蟒蛇 –

+1

也许你可以试试[varycode(https://www.varycode.com/) –

回答

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); 
       } 
      } 
     } 
    } 
} 

东西试试这个,一些你想做的事可以OS具体为在其操作系统处理文件的方式是什么,咬它应该工作。基本上这是搜索一个字符串,并重命名该文件以仅包含该字符串之前的内容。它可以处理给定目录中的所有文件。

我没有添加仅用于执行特定文件扩展名的功能,但这并不难实现。

+0

不知道如何renameTo()行为完全,所以它可能会留下一堆空白文件与新名称... –

+0

我开始阅读和everthing,但newFileName回来空白搜索:unt 打印子女姓名untitled.3ds 打印重命名 打印子名称untitled.stl 打印重命名 –

0

我做了一些改变,但我注意到文件正在重命名并移动到项目目录。我尝试添加路径,但没有运气。

public class Test { 

public static String folder = new String("C:/Users/XXX/XXX/XXX"); 
static String temp = "es"; 


public static void main(String[] args) throws IOException { 
    //Display Message on Screen 
    //System.out.println(String.format("%s", "Reading Files under the folder " + folder)); 
    try { 
     renameFiles(folder, temp); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

} 

public static void renameFiles(String dir, String search) throws IOException { 
    System.out.println("Searching for: " + search); 
    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); 
       System.out.println("Printing Child Name " + child.getName()); 
       String newFileName = child.getName().replace(search, ""); 
       System.out.println("Printing Rename " + dir + "/"+ newFileName); 
       File newFile = new File(newFileName); 
       child.renameTo(newFile); 
      } 
    } 
} 

}