class="java" name="code">package test; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; public class MultiFileNaming{ AtomicInteger s=new AtomicInteger(); public static void main(String[] args) throws IOException { String name="aa.txt"; final String regex="("+name.substring(0,name.indexOf("."))+"\\([\\d+]\\)\\."+name.substring(name.indexOf(".")+1)+")|("+name+")"; String dir=System.getProperty("user.dir"); File file=new File(dir); synchronized (file) { File[] listFiles=file.listFiles(new FilenameFilter(){ @Override public boolean accept(File dir, String name) { return name.matches(regex); } }); //说明已经存在 if(listFiles.length>0){ name=name.substring(0,name.indexOf("."))+"("+listFiles.length+")."+name.substring(name.indexOf(".")+1); } File newFile=new File(dir,name); newFile.createNewFile(); } } }
? ?结果:
?其中aa就是所要生成的文件 同名文件aa(1).txt ,aa(2).txt
?
? ?