如何判断文件夹中是否已存在同名文件 Java实现问题求助
问题根因
你的代码执行逻辑顺序出错了:你先调用new FileWriter(file)构造输出流,再执行file.exists()判断文件是否存在。而FileWriter的默认构造方法会直接触发两个行为:
- 若目标文件不存在,直接创建空的同名文件
- 若目标文件已存在,直接清空原有内容
这就导致你后续判断文件是否存在完全失效,就算用户选择不覆盖,原有文件的内容也已经被清空了。
修复方案
调整逻辑顺序:先判断文件是否存在、完成覆盖确认后,再构造FileWriter写入内容,修复后的代码如下:
if (option == JFileChooser.APPROVE_OPTION) { file = new File(fileChooser.getSelectedFile().toString() + ".html"); FileWriter writer = null; try { // 先判断文件是否存在,再处理写入逻辑 boolean needWrite = true; if (file.exists()) { int ergebnis = JOptionPane.showConfirmDialog(TiltungsplanGUI.this, "该文件已存在,是否覆盖?", "提示", JOptionPane.YES_NO_OPTION); if (ergebnis != JOptionPane.YES_OPTION) { needWrite = false; } } // 确认需要写入时再创建输出流、写入内容 if (needWrite) { writer = new FileWriter(file); writer.write(r.getTilgungsplan()); } } catch (IOException e1) { JOptionPane.showMessageDialog(TiltungsplanGUI.this, e1.getMessage()); } catch (RatenRechnerException e1) { JOptionPane.showMessageDialog(TiltungsplanGUI.this, e1.getMessage()); } finally { // 输出流放到finally块关闭,避免异常时资源泄漏 if (writer != null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } }
额外优化点
- 把流关闭逻辑放到
finally块中执行,避免代码抛出异常时输出资源没有正常关闭,导致文件被占用 - 新增是否需要写入的标记位,避免用户选择不覆盖时无意义的资源创建操作
内容的提问来源于stack exchange,提问作者Chris 344
相关产品推荐
相关产品推荐

