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.

}<br />

}<br />

for (int i = 0; i < args.length; i++) {<br />

try {<br />

typeFile(args[i]);<br />

if (i+1 < args.length) { // more files to type<br />

System.out.println();<br />

System.out.println("------------------------------------");<br />

}<br />

}<br />

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

}<br />

public static void typeFile(String filename) throws <strong>IO</strong>Exception {<br />

}<br />

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

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

fin.close();<br />

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

Untrusted applets are not usually allowed to read or write files. If your applet tries to create a<br />

FileInputStream , the constructor will throw a SecurityException.<br />

The FileInputStream class has one method that's not declared in the InputStream<br />

superclass, getFD().<br />

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

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

descriptor objects are discussed in Chapter 12. For now, all you can do with this object is use<br />

it to create another file stream. FileInputStream also has a protected finalize() method<br />

that's invoked when a FileInputStream object is garbage collected. This method ensures<br />

that files are properly closed before the file input stream that opened them is garbagecollected:<br />

protected void finalize() throws <strong>IO</strong>Exception<br />

You don't normally need to invoke this method explicitly, but if you subclass<br />

FileInputStream (something I've never found a need for), you must invoke<br />

super.finalize() from your subclass's finalize() method.<br />

It is possible to open multiple input streams to the same file at the same time, though it's<br />

rarely necessary to do so. Each stream maintains a separate pointer to the current position in<br />

the file. Reading from the file does not change the file in any way. Writing to a file is a<br />

different story, as you'll see in the next section.<br />

4.2 Writing Files<br />

The java.io.FileOutputStream class is a concrete subclass of java.io.OutputStream<br />

that provides output streams connected to files.<br />

public class FileOutputStream extends OutputStream<br />

53

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

Saved successfully!

Ooh no, something went wrong!