在下面的代码中,为什么当它说它已成功删除文件时,但当我检查文件仍然存在时。我将如何删除该文件。基本上,我正在尝试删除在使用它创建第二个文件后创建的第一个文件。
public static void main(String[] args) {
File file = new File("Hello");
try {
file.createNewFile();
} catch (Exception e) { }
try {
PrintWriter e = new PrintWriter(file);
e.println("Hello hi");
e.close();
}catch (Exception e) {}
File file2 = new File("Hello2");
try {
file2.createNewFile();
} catch (Exception e) {}
try {
Scanner x = new Scanner(file);
PrintWriter e = new PrintWriter(file);
while (x.hasNextLine()) {
System.out.println("Hello");}
e.close();
} catch (Exception e) {}
try {
file.delete();
System.out.println("It was deleted");
} catch (Exception e) { }
}
}
最佳答案
file.delete()
不会抛出 IOException
,它返回对 if
条件的 boolean 检查
if(file.delete())
{
System.out.println("File deleted successfully");
}
else
{
System.out.println("Failed to delete the file");
}
关于Java:如何删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47710004/