私は以下の正規表現を使用しています:
Pattern p = Pattern.compile("(.*?)(\\d+)?(\\..*)?");
while(new File(fileName).exists())
{
Matcher m = p.matcher(fileName);
if(m.matches()) { //group 1 is the prefix, group 2 is the number, group 3 is the suffix
fileName = m.group(1) + (m.group(2) == null ? "_copy" + 1 : (Integer.parseInt(m.group(2)) + 1)) + (m.group(3)==null ? "" : m.group(3));
}
}
これはfilenamelikeでも問題abc.txtなく動作しますが、名前の付いたファイルがある場合はabc1.txt、上記のメソッドが与えabc2.txtます。正規表現の条件を作成する方法、または新しいファイル名として(m.group(2) == null ? "_copy" + 1 : (Integer.parseInt(m.group(2)) + 1))返されるように変更する方法など。abc1_copy1.txtabc2.txtabc1_copy2