好吧,这会有点长。所以我做了一个junit测试类来测试我的程序。我想测试使用扫描仪将文件读入程序的方法是否抛出异常,如果文件不存在,如下所示:
@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
最佳答案
这里有两个问题。第一个是,如果在写入文件期间抛出异常,则输出流不会关闭(读取也是如此):
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 .
关于java - file.delete() 不会删除文件,java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20690247/