javadelete-fileaudioinputstream

Can't delete file after creating AudioInputStream from the file


I am working on a program for a class which involves creating a temporary audio file, reading data from it, and then deleting it. I have everything working, except deleting the file. When I attempt to delete the file, file.delete() returns false. I attempted to figure out exactly what was wrong using java.nio Files, and that returned that another process had the file open. After looking at my code, I narrowed it down to the AudioInputStream holding the file open. I can delete the file fine right before I create the AudioInputStream, however the file can't be deleted after it is created, despite that I close the stream before attempting to delete the file.

if (file != null && file.isFile())
{
    try
    {
       audioInputStream = null;
       try
       {
          audioInputStream = AudioSystem.getAudioInputStream(file);
       }  
       catch (Exception e)
       {
           System.out.println(e);
       }
       finally
       {
          audioInputStream.close();
       }    
       System.out.println("Attempted to delete wav file. Succesfull = " + file.delete());
    }
}

I have also tried placing the audioInputStream.close() after the catch and not in a finally with similar results.

Why is the inputstream keeping the file open after it is closed?


Solution

  • It should works if you wrapped by BufferedInputStream

    audioInputStream = AudioSystem.getAudioInputStream(new BufferedInputStream(Files.newInputStream(file.toPath())));
    

    Files is the class from nio

    import java.nio.file.Files;