I have a sound file that's recorded in my Java code and I need some 开发者_StackOverflow社区code to delete it.
What is so special about sound file??!!!
You can use this code.
public static void deleteFile(String file){
File myFile = new File(file);
if (!myFile.delete()){
System.out.println("Deletion was not sucessful");
}else{
System.out.println("File deleted");
}
}
Since the answer is so obvious (file.delete()
), I suspect that you're actually having issues with deleting it. I.e, file.delete()
has returned false
and the file is in reality not been deleted from the disk file system.
In that case, you can not delete it when you still have pointers open on that file. For example, when you have a InputStream
or OutputStream
on the file in your Java code, then you will not be able to delete the file as long as you do not call close()
on the streams.
So, to fix that issue, you need to ensure that you call close()
on any InputStream
and OutputStream
in the finally
block of the try
block where you're using the streams.
E.g.
File file = new File(name);
OutputStream output = null;
try {
output = new FileOutputStream(file);
// Write to output here ...
file.delete(); // Will always fail because output is not closed.
} finally {
if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
}
file.delete(); // Will succeed after close of output.
精彩评论