【发布时间】:2013-12-20 04:08:00
【问题描述】:
好的,这会有点长。所以我做了一个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
【问题讨论】:
-
也许不完全是你的问题,但你确定你的代码中除了 FileNotFoundException 没有其他异常吗?例如,关闭流时出现问题等。因为捕获所有异常并仅处理 FileNotFoundException 会抛出所有其他异常,而不会让您知道发生了任何问题。
-
另外请记住,Windows 不会让您删除任何进程打开的任何文件。