23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

File f = new File("tmp/");<br />

f.mkdir();<br />

<strong>Java</strong> I/O<br />

The trailing slash is optional, but it helps you to remember that you're dealing with a directory<br />

rather than a plain file. If the security manager does not allow the directory to be created, a<br />

security exception is thrown. If the directory cannot be created for any other reason, mkdir()<br />

returns false. The mkdir() method only works for single directories. Trying to create a<br />

directory like com/macfaq/io/ with mkdir() only works if com/macfaq already exists.<br />

The mkdirs() method creates every directory in a path that doesn't already exist:<br />

public boolean mkdirs()<br />

For example:<br />

File f = new File("com/macfaq/io/");<br />

f.mkdirs();<br />

mkdirs() returns true if all directories in this path are created or already exist and false if<br />

only some or none of them are created. If mkdirs() returns false, you need to test each<br />

directory in the path to see whether it was created, because the invocation could have been<br />

partially successful.<br />

One reason mkdir() and mkdirs() may return false (fail to create a directory) is that a file<br />

already exists with the name the directory has. Neither mkdir() nor mkdirs() will overwrite<br />

an existing file or directory.<br />

12.3.7.2 Listing directories<br />

The list() method returns an array of strings containing the names of each file in the<br />

directory referred to by the File object:<br />

public String[] list()<br />

This method returns null if the File object doesn't point to a directory. It throws a security<br />

exception if the program isn't allowed to read the directory being listed. An alternative version<br />

of list() uses a FilenameFilter object (discussed later in the chapter) to restrict which<br />

files are included in the list:<br />

public String[] list(FilenameFilter filter)<br />

Example 12.5 is a simple character-mode program that recursively lists all the files in a<br />

directory, and all the files in directories in the directory, and all the files in directories in the<br />

directory, and so on. Files are indented two spaces for each level deep they are in the<br />

hierarchy.<br />

Example 12.5. The DirList Program<br />

import java.io.*;<br />

import java.util.*;<br />

296

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!