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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

12.3.4 Manipulating Files<br />

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

The File class has methods to create, move, rename, and delete files. A method to copy files<br />

is a noticeable omission.<br />

12.3.4.1 Creating files<br />

<strong>Java</strong> 1.1 provides no method to create a new file. Opening a file output stream to the file you<br />

want to create, then immediately closing it, has the same effect. For example, the following<br />

method creates a file if, and only if, it doesn't already exist. Otherwise, it throws an<br />

<strong>IO</strong>Exception:<br />

public static void createFileSafely(File f) throws <strong>IO</strong>Exception {<br />

}<br />

if (f.exists()) {<br />

throw new <strong>IO</strong>Exception(f.getName() + " already exists.");<br />

}<br />

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

fout.close();<br />

<strong>Java</strong> 2 adds the createNewFile() method:<br />

public boolean createNewFile() throws <strong>IO</strong>Exception // <strong>Java</strong> 2<br />

This method checks to see whether the file exists and creates the file if it doesn't already exist.<br />

It returns true if the file was created and false if it wasn't created, either because it couldn't<br />

be created or because the file already existed. For example:<br />

File f = new File("output.dat");<br />

boolean success = f.createNewFile();<br />

if (success) {<br />

//...<br />

}<br />

else { //...<br />

This method throws an <strong>IO</strong>Exception if an I/O error occurs. It throws a security exception if<br />

the security manager vetoes the creation of the file.<br />

12.3.4.2 Moving and renaming files<br />

The renameTo() method changes the name of a file:<br />

public boolean renameTo(File destination)<br />

For example, to change the name of the file src.txt in the current working directory to dst.txt,<br />

you would write:<br />

File src = new File("src.txt");<br />

File dst = new File("dst.txt");<br />

src.renameTo(dst);<br />

As well as renaming the source file, renameTo()moves the source file from its original<br />

directory to the directory specified by the destination argument if the destination file is in a<br />

291

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

Saved successfully!

Ooh no, something went wrong!