importjava.io.File;// Import the File classpublicclassDeleteFile{publicstaticvoidmain(String[] args){File myObj =newFile("filename.txt");if(myObj.delete()){System.out.println("Deleted the file: "+ myObj.getName());}else{System.out.println("Failed to delete the file.");}}}
输出将是:
Deleted the file: filename.txt
删除文件夹
您也可以删除文件夹。但是,它必须为空:
importjava.io.File;publicclassDeleteFolder{publicstaticvoidmain(String[] args){File myObj =newFile("C:\\Users\\MyName\\Test");if(myObj.delete()){System.out.println("Deleted the folder: "+ myObj.getName());}else{System.out.println("Failed to delete the folder.");}}}