Cannot delete file but writers are closed

97 views Asked by At

This is my code writing in a file..

FileOutputStream fos = new FileOutputStream( fileTAG, true );
OutputStreamWriter osw = new OutputStreamWriter( fos, strFileEncoding );
buf = new BufferedWriter( osw );
buf.write( strTagStream );
buf.newLine();
buf.flush();
if ( buf != null )
{
    buf.close();
}
if ( osw != null )
{
    osw.close();
}
if ( fos != null )
{
    fos.close();
}

This is my code first deleting the files and afterwards deleting the directory:

File[] arrFiles = fileTagpath.listFiles();
for ( File fileCurrentFile : arrFiles )
{
    if ( !fileCurrentFile.delete() )
    {
        String strMessage = "File <" + fileCurrentFile.getAbsolutePath() + "> has not been deleted.";
        System.out.println( strMessage );
        fail( strMessage );
    }
}
if ( !fileTagpath.delete() )
{
    String strMessage = "Directory <" + fileTagpath.getAbsolutePath() + "> has not been deleted.";
    System.out.println( strMessage );
    fail( strMessage );
}

It fails with the message that the file has not been deleted. The output shows the right file and the right directory. If I copy the path to my explorer window I get to the right file. The files path is under

C:\Users\xxx\AppData\Local\Temp\tag

What's my mistake?

1

There are 1 answers

1
TCPN On BEST ANSWER

In java if you want to use backslash. Try like this

Your path: C:\Users\xxx\AppData\Local\Temp\tag

but, you have to always double backslash follow below:

C:\\Users\\xxx\\AppData\\Local\\Temp\\tag