2016-11-26 123 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); 
      } 
    } 
} 

}