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

The FileOutputStream class has one method that's not declared in java.io.OutputStream,<br />

getFD():<br />

public final FileDescriptor getFD() throws <strong>IO</strong>Exception<br />

This method returns the java.io.FileDescriptor object associated with this stream.<br />

The FileOutputStream class also has a protected finalize() method that's invoked before<br />

a FileOutputStream object is garbage-collected. This method ensures that files are properly<br />

flushed and closed before the file output stream that opened them is garbage-collected. You<br />

normally don't need to invoke this method explicitly. If you subclass FileOutputStream and<br />

override finalize(), the subclass's finalize() method should invoke this finalize()<br />

method by calling super.finalize().<br />

Example 4.2 reads two filenames from the command line, then copies the first file into the<br />

second file. The StreamCopier class from Example 3.3 in the last chapter is used to do the<br />

actual reading and writing.<br />

Example 4.2. The FileCopier Program<br />

import java.io.*;<br />

import com.macfaq.io.*;<br />

public class FileCopier {<br />

public static void main(String[] args) {<br />

}<br />

if (args.length != 2) {<br />

System.err.println("Usage: java FileCopier infile outfile");<br />

}<br />

try {<br />

copy(args[0], args[1]);<br />

}<br />

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

public static void copy(String inFile, String outFile)<br />

throws <strong>IO</strong>Exception {<br />

FileInputStream fin = null;<br />

FileOutputStream fout = null;<br />

try {<br />

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

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

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

}<br />

finally {<br />

try {<br />

if (fin != null) fin.close();<br />

}<br />

catch (<strong>IO</strong>Exception e) {<br />

}<br />

try {<br />

if (fout != null) fout.close();<br />

}<br />

catch (<strong>IO</strong>Exception e) { }<br />

55

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

Saved successfully!

Ooh no, something went wrong!