The File class is not a stream-based class. Instead of working with streams, the File class provides you with an interface into the file and directory structure of your underlying file system. It contains a number of file-based utilities, such as the ability to delete files and to create temporary files. When writing tests that work with files, you want to ensure that you have a clean environment for testing. You also want to ensure that you leave things the way they were when the test completes. With respect to testFiled-Report, this means that you need to delete any existing report file as the first step in the test and delete the created report file as the last step in the test. public void testFiledReport() throws IOException { final String filename = "testFiledReport.txt"; try { delete(filename); new RosterReporter(session).writeReport(filename); StringBuffer buffer = new StringBuffer(); String line; BufferedReader reader = new BufferedReader(new FileReader(filename)); while ((line = reader.readLine()) != null) buffer.append(String.format(line + "%n")); reader.close(); assertReportContents(buffer.toString()); } finally { delete(filename); } } private void delete(String filename) { File file = new File(filename); if (file.exists()) assertTrue("unable to delete " + filename, file.delete()); } The delete method uses the File class to accomplish its goals. It creates a File object by passing a filename to its constructor. It calls the exists method to determine whether the file can be found in the file system. Finally, it calls the delete method, which returns true if the file system successfully removed the file, false otherwise. A file system might not be able to delete a file if it is locked or has its read-only attribute set, among other reasons. I have categorized most of the functionality of the class java.io.File in Table 11.1.
|