假设我要在桌面输出123.txt,如果桌面上已有123.txt,就输出123(1).txt
如果连123(1).txt都有了,就输出123(2).txt请问该怎样做?谢谢~

解决方案 »

  1.   

    用java.io.File.exists()方法判断文件是否存在,如果存在则计算文件的个数,并将个数加1添加到文件名的后面;
      

  2.   


    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    public class FileSave {
    public static void main(String[] args) throws IOException {
    File file = new File("d:\\123.txt");
    int i = 1;
    String path = file.getAbsolutePath();
    path = path.substring(0, path.lastIndexOf("\\"));
    String fileName = file.getName();
    while(file.exists()) {
    String name;
    String type = fileName.substring(fileName.lastIndexOf(".") + 1);
    name = fileName.substring(0, fileName.lastIndexOf("."));
    name = path + "\\" +  name + "(" + i + ")." + type ;
    file = new File(name);
    i++;
    }
    FileOutputStream fos = new FileOutputStream(file);
    fos.close();
    System.out.println("文件保存成功");
    }
    }
    这里大概实现了一个,楼主可以看看!