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

我正在尝试将文件另存为* .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) 。 请帮我一下

你正在做检查错误,而不是检查variablesexists1 ,你检查是否存在 ,这是从循环部分之前是真实的。

尝试改变如下。

 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; } 

在检查文件存在的情况下,你没有做任何事情吗? 不要在名称中追加任何内容,因此如果文件存在,它将继续并尝试只保存相同的名称。 一旦发现文件存在,请尝试追加