file.delete()返回false,即使file.exists(),file.canRead(),file.canWrite(),file.canExecute()都返回true我正在尝试删除文件,在写完文件后,用FileOutputStream。这是我用来编写的代码:private void writeContent(File file, String fileContent) {
FileOutputStream to;
try {
to = new FileOutputStream(file);
to.write(fileContent.getBytes());
to.flush();
to.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}如图所示,我刷新并关闭流,但是当我尝试删除时,file.delete()返回false。我删除前检查,看看是否该文件存在,并且:file.exists(),file.canRead(),file.canWrite(),file.canExecute()所有返回true。在调用这些方法后,我尝试file.delete()返回false。有什么我做错了吗?
3 回答

蓝山帝景
TA贡献1843条经验 获得超7个赞
Java中的另一个错误。我很少找到他们,只是我10年职业生涯中的第二个。正如其他人所提到的,这是我的解决方案。我有幽冥使用过System.gc()
。但就我而言,这绝对是至关重要的。奇怪的?是!
finally{ try { in.close(); in = null; out.flush(); out.close(); out = null; System.gc(); } catch (IOException e) { logger.error(e.getMessage()); e.printStackTrace(); }}

梵蒂冈之花
TA贡献1900条经验 获得超5个赞
这个诀窍很奇怪。事情是我以前读过文件的内容,我用过BufferedReader
。读完后,我关闭了缓冲区。
同时我换了,现在我正在阅读内容FileInputStream
。完成阅读后,我关闭了流。现在它正在发挥作用。
问题是我对此没有解释。
我不知道BufferedReader
也FileOutputStream
不相容。

炎炎设计
TA贡献1808条经验 获得超4个赞
我尝试过这个简单的事情似乎很有效。
file.setWritable(true);file.delete();
这个对我有用。
如果这不起作用,请尝试使用sudo运行Java应用程序(如果在Linux上)和管理员运行Windows时。只是为了确保Java有权更改文件属性。
添加回答
举报
0/150
提交
取消