file.delete() returns false even though file.exist

2019-01-01 07:07发布

I'm trying to delete a file, after writing something in it, with FileOutputStream. This is the code I use for writing:

private void writeContent(File file, String fileContent) {
    FileOutputStream to;
    try {
        to = new FileOutputStream(file);
        to.write(fileContent.getBytes());
        to.flush();
        to.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

As it is seen, I flush and close the stream, but when I try to delete, file.delete() returns false.

I checked before deletion to see if the file exists, and: file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true. Just after calling these methods I try file.delete() and returns false.

Is there anything I've done wrong?

16条回答
孤独总比滥情好
2楼-- · 2019-01-01 07:29

I tried this simple thing and it seems to be working.

file.setWritable(true);
file.delete();

It works for me.

If this does not work try to run your Java application with sudo if on linux and as administrator when on windows. Just to make sure Java has rights to change the file properties.

查看更多
深知你不懂我心
3楼-- · 2019-01-01 07:33

if file.delete() is sending false then in most of the cases your Bufferedreader handle will not be closed. Just close and it seems to work for me normally.

查看更多
忆尘夕之涩
4楼-- · 2019-01-01 07:34

The problem could be that the file is still seen as opened and locked by a program; or maybe it is a component from your program that it had been opened in, so you have to ensure you use the dispose() method to solve that problem. i.e. JFrame frame; .... frame.dispose();

查看更多
旧人旧事旧时光
5楼-- · 2019-01-01 07:38

I had the same problem on Windows. I used to read the file in scala line by line with

Source.fromFile(path).getLines()

Now I read it as a whole with

import org.apache.commons.io.FileUtils._

// encoding is null for platform default
val content=readFileToString(new File(path),null.asInstanceOf[String])

which closes the file properly after reading and now

new File(path).delete

works.

查看更多
登录 后发表回答