importjava.io.*;publicclassMain{publicstaticvoidmain(String[] args){try{BufferedWriter out =newBufferedWriter(newFileWriter("filename"));
out.write("aString1\n");
out.close();boolean success =(newFile("filename")).delete();if(success){System.out.println("The file has been successfully deleted");}BufferedReader in =newBufferedReader(newFileReader("filename"));String str;while((str = in.readLine())!=null){System.out.println(str);}
in.close();}catch(IOException e){System.out.println("exception occoured"+ e);System.out.println("
File does not exist or you are trying to read a file that has been deleted");}}}
结果
上面的代码示例将产生以下结果。
The file has been successfully deleted
exception occouredjava.io.FileNotFoundException:filename(The system cannot find the file specified)File does not exist or you are trying to read a
file that has been deleted
下面是另一个在 Java 中删除文件的示例
importjava.io.File;publicclassDeleteFileExample{publicstaticvoidmain(String[] args){try{File file =newFile("C:\\Users\\TutorialsPoint7\\Desktop\\abc.txt");if(file.delete()){System.out.println(file.getName()+" is deleted!");}else{System.out.println("Delete operation is failed.");}}catch(Exception e){
e.printStackTrace();}}}