如何保存文件而不覆盖现有的同名文件

时间:2017-09-05 10:03:15

标签: java excel file rename

我正在尝试将文件另存为* .xlsx,而不会覆盖具有相同名称的现有文件。我想将数字后缀添加到新文件名,例如file(1).xlsx,file(2).xlsx,以防仅在指定文件存在的情况下。这是我到目前为止所尝试的:

do {
  s = JOptionPane.showInputDialog("Enter the name of the file name");
  File tmpDir = new File(System.getProperty("user.home"), "Documents\\Challan_Reports\\" + s + ".xlsx");

  boolean exists = tmpDir.exists();
  if (exists) {
    JOptionPane.showMessageDialog(this, "File Name Already exists try again!");

  }
  else {
    break;
  }
} while (true);
if (s.equals("") || s.equals(null)) {
  //.........................................................................
  File tmpDir = new File(System.getProperty("user.home"), "Documents\\Challan_Reports\\" + gname + " " + date + ".xlsx");
  boolean exists = tmpDir.exists();
  if (exists) {
    JOptionPane.showMessageDialog(this, "exists 1");
    for (int m= 1; true;m++)
    {
      JOptionPane.showMessageDialog(this, "exists m " + m);
      File tmpDir1 = new File(System.getProperty("user.home") + "\\Documents\\Challan_Reports\\" + gname + " " + date + " (" + m + ").xlsx");
      System.out.println(System.getProperty("user.home") + "\\Documents\\Challan_Reports\\" + gname + " " + date + " (" + m + ").xlsx");
      boolean exists1 = tmpDir1.exists();
      if (exists) {
        System.out.println("exists file");
        continue;
      }
      else {

        System.out.println(" not exists");
        filename = System.getProperty("user.home") + "\\Documents\\Challan_Reports\\" + gname + " " + date + " (" + m + ").xlsx";
        break;
      }
    }
  }
  //      FileOutputStream out = new FileOutputStream(new File(System.getProperty("user.home"),"Documents\\Challan_Reports\\"+gname+" "+date+".xlsx"));
  // workbook.write(out);
  // out.close();
}
FileOutputStream out = new FileOutputStream(new File(filename));
workbook.write(out);
out.close();
System.out.println(
  "Writesheet.xlsx written successfully");
JOptionPane.showMessageDialog(this, filename + ".xlsx \n\\Generated at path" + System.getProperty("user.home") + "\\Documents\\Challan_Reports");
      }
     catch(Exception e) {
  JOptionPane.showMessageDialog(null, e);
}

问题在于它将输出作为文件(1)或文件(2).....存在 什么时候没有。如果我将条件设置为If,则循环中的if(!exists)条件仅在第一次起作用。请帮帮我。

2 个答案:

答案 0 :(得分:1)

您正在检查错误,而是检查变量 exists1 ,您正在检查存在,并且在 for循环部分之前确实如此。

尝试更改如下。

boolean exists1 = tmpDir1.exists();
     if(exists1)// change here exists to exists1
     {
          System.out.println("exists file");
          continue;
     }
     else{

         System.out.println(" not exists");
         filename=System.getProperty("user.home")+"\\Documents\\Challan_Reports\\"+gname+" "+date+" ("+m+").xlsx";
         break;
     }

答案 1 :(得分:0)

在您检查文件存在的情况下,您没有做任何正确的事情?不附加任何名称,因此如果文件存在,它将继续并尝试仅保存相同的名称。一旦找到文件存在,请尝试附加