在本教程中,我们将看到如何在 java 中删除文件。我们将使用delete()
方法删除文件。
public boolean delete()
如果指定的File
成功删除,则此方法返回true
,否则返回false
。
这是完整的代码:
import java.io.File;
public class DeleteFileJavaDemo
{
public static void main(String[] args)
{
try{
//Specify the file name and path
File file = new File("C:\\myfile.txt");
/*the delete() method returns true if the file is
* deleted successfully else it returns false
*/
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete failed: File didn't delete");
}
}catch(Exception e){
System.out.println("Exception occurred");
e.printStackTrace();
}
}
}
输出:
myfile.txt is deleted!