使用java重命名特定目录上的相同文件

使用java重命名特定目录上的相同文件,java,r.java-file,Java,R.java File,首先感谢您抽出时间 我需要替换特定directoryTEMP中相同文件的名称。我的问题是,我有x个相同的文件,其结构如下:timestamp_filename.txt,我需要将此结构替换为filename_count.txt 例如,我有两个带有timestamp_file.txt的文件,我想用file.txt和file_1.txt替换它们 获取所有文件不是一件可以完成的事情,因为临时文件夹可能会增长很多 谢谢 将FilenameFilter对象和正则表达式结合使用,以检索临时文件夹中匹配文件的列

首先感谢您抽出时间

我需要替换特定directoryTEMP中相同文件的名称。我的问题是,我有x个相同的文件,其结构如下:timestamp_filename.txt,我需要将此结构替换为filename_count.txt

例如,我有两个带有timestamp_file.txt的文件,我想用file.txt和file_1.txt替换它们

获取所有文件不是一件可以完成的事情,因为临时文件夹可能会增长很多

谢谢

将FilenameFilter对象和正则表达式结合使用,以检索临时文件夹中匹配文件的列表

然后使用自定义比较器对结果列表进行排序,以便具有相同“文件”部分但不同“时间戳”部分的所有文件彼此相邻,以简化生成_1、_2、。。。版本

然后遍历结果列表,适当地重命名/移动文件

下面是一个使用正则表达式匹配文件名的文件名筛选器示例:

public class REFilenameFilter implements FilenameFilter {

    /** The regular expression to use when matching file names. */
    final String regularExpression;


    /**
     * Constructor.
     *
     * @param expression the regular expression to use when matching file names.
     */
    public REFilenameFilter(final String expression) {
        regularExpression = expression;
    }


    /**
     * Returns true if the file matches the regular expression.
     *
     * @param dir the directory containing the file.
     * @param name the name of the file.
     * @return true if the name of the file matches the regular expression, otherwise false.
     */
    public boolean accept(final File dir, final String name) {
        // return true if the name matches the regular expression
        return name.matches(regularExpression);
    }

}
下面是一个示例比较器,假设您的时间戳很长:

public class TempFileComparator implements Comparator<File> {

    public int compare(final File file1, final File file2) {
        String[] parts1 = file1.getName().split("_");
        String[] parts2 = file2.getName().split("_");

        int comp = parts1[1].compareTo(parts2[1]);
        if(comp == 0) {
            Long timestamp1 = Long.parseLong(parts1[0]);
            Long timestamp2 = Long.parseLong(parts2[0]);
            comp = timestamp1.compareTo(timestamp2);
        }

        return comp;
    }

}

打开一个目录流,对所选目录中的所有文件进行迭代/循环。然后对文件使用move方法适当地重命名它们。请查看此链接以获取帮助: