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

in Apple's Macintosh Runtime for <strong>Java</strong>, shown in Figure 1.5, provides a simple pop-up menu<br />

interface for selecting a file, /dev/null, or a message window as the target of System.out or<br />

source for System.in.<br />

Figure 1.5. Redirecting stdout and stdin from JBindery<br />

It's sometimes convenient to be able to redirect System.out, System.in, and System.err<br />

from inside the running program. The following three static methods in the<br />

java.lang.System class do exactly that:<br />

public static void setIn(InputStream in)<br />

public static void setOut(PrintStream out)<br />

public static void setErr(PrintStream err)<br />

For example, to specify that data written on System.out is sent to the file yankees99.out and<br />

data read from System.in comes from yankees99.tab, you could write:<br />

System.setIn(new FileInputStream("yankees99.tab"));<br />

System.setOut(new PrintStream(new FileOutputStream("yankees99.out")));<br />

These methods are especially useful when making a quick and dirty port of a program that<br />

makes heavy use of System.out, System.in, or System.err from an application to an<br />

applet. However, there is no absolute guarantee that console redirection will be allowed in all<br />

web browsers. Internet Explorer 4.0b2 allowed it, but the released version does not. Hot<strong>Java</strong><br />

1.1 allows it with the security settings turned down, but not with security at the default level.<br />

Netscape Navigator 4.0 and 4.5 and Hot<strong>Java</strong> 1.0 do not allow console redirection.<br />

The SecurityManager class does not have a specific method to test whether or not<br />

redirecting System.out or System.err is allowed. However, in <strong>Java</strong> 1.1 Sun's JDK checks<br />

whether this is permitted by calling checkExec("set<strong>IO</strong>"). (The source code contains a<br />

comment to the effect that there should be a separate method for this sort of check in future<br />

versions of <strong>Java</strong>.) checkExec() determines whether the security manager allows a subprocess<br />

called setio to be spawned. The AppletSecurity security manager used by appletviewer in<br />

JDK 1.1 always disallows this call.<br />

31

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

Saved successfully!

Ooh no, something went wrong!