file.delete()不会删除文件,java

时间:2013-12-19 19:37:52

标签: java file-io

好的,这会有点长。所以我做了一个junit测试类来测试我的程序。我想测试一个使用Scanner读取文件到程序中的方法是否抛出异常,如果该文件不存在,如下:

@Test
public void testLoadAsTextFileNotFound()
{
    File fileToDelete = new File("StoredWebPage.txt");  

    if(fileToDelete.delete()==false) {
        System.out.println("testLoadAsTextFileNotFound - failed");
        fail("Could not delete file");
    }

    try{    
        assertTrue(tester.loadAsText() == 1);
        System.out.println("testLoadAsTextFileNotFound - passed");
    } catch(AssertionError e) {
        System.out.println("testLoadAsTextFileNotFound - failed");
        fail("Did not catch Exception");

    }
}

但测试失败了“无法删除文件”,所以我做了一些搜索。路径是正确的,我对文件有权限,因为程序首先创建它。所以唯一的另一个选择是,来自文件的流仍然在运行。所以我检查了方法,以及使用该文件的另一种方法,并且尽可能地,两个流都在方法内部关闭。

protected String storedSite; //an instance variable
/**
* Store the instance variable as text in a file
*/
public void storeAsText()
{
    PrintStream fileOut = null;
    try{
        File file = new File("StoredWebPage.txt");
        if (!file.exists()) {
            file.createNewFile();
        }

        fileOut = new PrintStream("StoredWebPage.txt");
        fileOut.print(storedSite);
        fileOut.flush();
        fileOut.close();

    } catch(Exception e) {
        if(e instanceof FileNotFoundException) {
            System.out.println("File not found");
        }
        fileOut.close();
    } finally {
        if(fileOut != null)
            fileOut.close();
    }
}

/**
* Loads the file into the program
*/
public int loadAsText()
{
    storedSite = ""; //cleansing storedSite before new webpage is stored
    Scanner fileLoader = null;
    try {
        fileLoader = new Scanner(new File("StoredWebPage.txt"));
        String inputLine;
        while((inputLine = fileLoader.nextLine()) != null)
            storedSite = storedSite+inputLine;
        fileLoader.close();
    } catch(Exception e) {
        if(e instanceof FileNotFoundException) {
            System.out.println("File not found");
            return 1;
        }
        System.out.println("an Exception was caught");
        fileLoader.close();
    } finally {
        if(fileLoader!=null)
            fileLoader.close();
    }

    return 0; //return value is for testing purposes only
}

我没有想法。为什么我不能删除我的文件?

编辑:我编辑了代码,但这仍然给我带来了同样的问题:S

1 个答案:

答案 0 :(得分:3)

这里有两个问题。第一个是如果在写入文件期间抛出异常,则输出流不会关闭(读取相同):

try {
    OutputStream someOutput = /* a new stream */;

    /* write */

    someOutput.close();

第二个问题是,如果有异常,则不会通知您:

} catch (Exception e) {
    if (e instanceof FileNotFoundException) {
        /* do something */
    }

    /* else eat it */
}

所以问题几乎肯定是抛出了一些其他异常,而你却不知道它。

关闭流的“正确”惯用法如下:

OutputStream someOutput = null;
try {
    someOutput = /* a new stream */;

    /* write */

} catch (Exception e) {
    /* and do something with ALL exceptions */

} finally {
    if (someOutput != null) someOutput.close();
}

或者在Java 7中,您可以使用try-with-resources