java.io.File


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.

Table 11.1. java.io.File methods by category

Category

Methods

temporary file creation

createTempFile

empty file creation

createNewFile

file manipulation

delete, deleteOnExit, renameTo

file and path name queries

getAbsoluteFile, getAbsolutePath, getCanonicalFile, getCanonicalPath, getName, getPath, toURI, toURL

classification

isFile, isDirectory

attribute query/manipulation

isHidden, lastModified, length, canRead, canWrite, setLastModified, setReadOnly

directory query/manipulation

exists, list, listFiles, listRoots, mkdir, mkdirs, getParent, getParentFile




Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net