【问题标题】:How rename files using java [duplicate]如何使用java重命名文件[重复]
【发布时间】:2017-04-10 10:06:47
【问题描述】:

我有一个可以从文件名中删除字符串的 python 程序,但我正在寻求使用 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)

【问题讨论】:

  • 我们理解你,但你应该向我们展示一些 java 代码而不是 python
  • 或许你可以试试varycode

标签: java


【解决方案1】:
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);
                }  
            }
        }
    }
}

试试这个,你想做的一些事情可以是操作系统特定的,关于操作系统处理文件的方式,它应该可以工作。基本上,它的作用是搜索一个字符串并将文件重命名为仅包含该字符串之前的内容。它对给定目录中的所有文件执行此操作。

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

【讨论】:

  • 不确定 renameTo() 的行为如何,因此可能会留下一堆带有新名称的空白文件...
  • 我可以阅读所有内容,但 newFileName 返回空白正在搜索:unt Printing Child Name untitled.3ds Printing Rename Printing Child Name untitled.stl Printing Rename
猜你喜欢
  • 2014-01-20
  • 2010-11-12
  • 2011-12-18
  • 2014-08-03
  • 2016-05-19
  • 2020-07-02
  • 1970-01-01
  • 1970-01-01
  • 2018-09-03
相关资源
最近更新 更多