【问题标题】:How to add Special characters to the file name in this case在这种情况下如何在文件名中添加特殊字符
【发布时间】:2016-11-24 12:06:28
【问题描述】:

在存储文件之前,我会检查文件名是否已经存在(以防止覆盖)

为此,我使用以下代码

import java.io.File;
import java.util.ArrayList;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Test {
    public static void main(String[] args) {
        String imagename = checkImage("big_buck_bunny.mp4");
        System.out.println(imagename);
    }

    public static String checkImage(String image_name) {
        String newimage = "";
        ArrayList<String> image_nameslist = new ArrayList<String>();
        File file = new File("C:\\Users\\Public\\Videos\\Sample Videos\\");
        File[] files = file.listFiles();
        for (File f : files) {
            image_nameslist.add(f.getName());
        }
        long l = System.currentTimeMillis();
        if (image_nameslist.contains(image_name)) {
            Random randomGenerator = new Random();
            int randomInt = randomGenerator.nextInt(100);
            Matcher matcher = Pattern.compile("(.*)\\.(.*?)").matcher(image_name);
            if (matcher.matches()) { // <== test input filename is OK?
                newimage = String.format("%s_%d.%s", matcher.group(1),randomInt, matcher.group(2));
            }
        }
        else {
            newimage = image_name;
        }
        return newimage;
    }
}

我得到的输出是

big_buck_bunny_50.mp4

上面代码中的randomInt,是否可以在前后加一些特殊字符@,这样输出看起来像\

big_buck_bunny_@50@.mp4

【问题讨论】:

  • 你试过了吗?如果操作系统接受它应该不是问题。
  • 我认为你最好不要这样检查文件名。如果不同的文件名引用同一个文件,例如不区分大小写的文件系统,它将失败。最好使用exists() 方法创建File 对象abd 检查。同样在您的代码中,不能保证 newimage 不存在。

标签: java


【解决方案1】:

只需使用您的随机整数形成一个带有特殊字符的字符串,然后将其包含在对String.format() 的调用中。我对您的电话所做的唯一更改是将%d 替换为%s 并使用随机字符串而不是随机整数。

String randStr = "@" + String.valueOf(randomInt) + "@";
newimage = String.format("%s_%s.%s", matcher.group(1), randStr, matcher.group(2));

但是,您确定您的操作系统接受/推荐此类文件名吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多