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.

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

• Do not parse pathnames to find directories. Use the methods of the java.io.File<br />

class instead.<br />

• Do not use renameTo() for anything except renaming a file. In particular, do not use it<br />

to move a file.<br />

• Try to avoid moving and copying files from within <strong>Java</strong> programs if at all possible.<br />

• Do not use . to refer to the current directory. Use System.getProperty<br />

("user.dir") instead.<br />

• Do not use .. to refer to the parent directory. Use getParent() instead.<br />

• Do not assume the current working directory is the one where your .class files live. It<br />

almost certainly won't be that directory on the Mac, and it may not be on other<br />

platforms, including Windows and Unix.<br />

• Place any data files your program requires in JAR archives rather than directly in the<br />

filesystem, then load them as resources from the class path.<br />

• When in doubt, it never hurts to convert filenames to canonical form.<br />

• Do not assume anything about filesystem conventions. Some platform somewhere will<br />

surprise you. (Have you tested your program on BeOS yet?)<br />

• Test your code on as many different filesystems as you can get your hands on.<br />

Despite all the problems I've pointed out, it is mostly possible to write robust file access code<br />

that works across all platforms where <strong>Java</strong> runs. But doing so requires understanding, effort,<br />

and thought. You cannot simply write for Windows or Unix and hope things will work out for<br />

the best on other platforms. You must plan to handle a wide range of filesystems and filename<br />

conventions.<br />

305

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

Saved successfully!

Ooh no, something went wrong!