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 />

When run, it creates files named mail30446.tem, mail30447.tem, etc. through mail30455.tem.<br />

By default, temporary files are placed in the directory named by the java.io.tmpdir<br />

property. On Unix, this is likely to be /tmp or /var/tmp. On Windows, it's probably C:\temp or<br />

C:\Windows\Temp. On the Mac, it's probably the invisible Temporary Items folder on the<br />

startup drive. You can specify a different directory using the third argument to<br />

createTempFile(). For instance, to create a temporary file in the current working directory:<br />

File cwd = new File(System.getProperty("user.dir"));<br />

File temp = File.createTempFile("rus", ".tmp", cwd);<br />

You often want to delete temporary files when your program exits. You can accomplish this<br />

by passing them to the deleteOnExit() method:<br />

public void deleteOnExit() // <strong>Java</strong> 2<br />

For example:<br />

File temp = File.createTempFile("mail", ".tem");<br />

temp.deleteOnExit();<br />

This method works on any File object, not just temporary files. Be careful, because there's no<br />

good way to cancel a request to delete files when your program exits.<br />

Temporary files are useful when you need to operate on a file in place. You can do this in two<br />

passes. In the first pass, you read from the file you're converting and write into the temporary<br />

file. In the second pass, you read from the temporary file and write into the file you're<br />

converting. Here's an example:<br />

try {<br />

File infile = new File(args[2]);<br />

File outfile = new File(args[3]);<br />

boolean usingTempFile = false;<br />

if (infile.getCanonicalPath().equals(outfile.getCanonicalPath())) {<br />

outfile = File.createTempFile("temp", null);<br />

outfile.deleteOnExit();<br />

usingTempFile = true;<br />

}<br />

// perform operations as normal, then close both files...<br />

if (usingTempFile) {<br />

FileInputStream fin = new FileInputStream(outfile);<br />

FileOutputStream fout = new FileOutputStream(infile);<br />

StreamCopier.copy(fin, fout);<br />

fin.close();<br />

fout.close();<br />

}<br />

}<br />

catch (<strong>IO</strong>Exception e) {System.err.println(e);}<br />

12.3.6 Utility Methods<br />

The File class also contains the usual equals(), hashCode(), and toString() methods,<br />

which behave exactly as you would expect. It does not contain a clone() method.<br />

294

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

Saved successfully!

Ooh no, something went wrong!