2017-09-05 417 views
0

我试图将文件另存为* .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),则循环中的条件只有第一次有效。请帮助我。

回答

0

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

1

你正在做检查的错误,不是检查变量exists1,你正在检查存在,这是真正的从之前循环一部分。

尝试更改如下。

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

thanx man..you saved my day –

+0

@ Mr.Hunt恭喜,您需要将答案标记为已接受。 –