java如何保存文件而不重写同名的现有文件
我正在尝试将文件另存为*。xlsx,而不覆盖同名的现有文件。我想给新文件名添加数字后缀,比如文件(1)。xlsx,文件(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)
时才起作用。请帮帮我
# 1 楼答案
在你检查文件存在的情况下,你没有做任何正确的事情吗?不在文件名中添加任何内容,因此如果文件存在,它将继续并尝试只保存相同的名称。一旦发现文件存在,请尝试追加
# 2 楼答案
您正在执行错误检查,而不是检查变量存在1,您正在检查存在,从之前的开始,对于循环部分,这是正确的
试着改变如下