13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

4.3 The System Class103named in, out, and err. You’ve probably already seen out in Java programswith statements like this:System.out.println("Hello, world.");You can also write:System.err.println("Error message here\n");andBufferedReader in = new BufferedReader(newInputStreamReader(System.in));while ((line = in.readLine()) != null) {...}Java parallels <strong>Linux</strong> nicely <strong>on</strong> I/O descriptors. If you redirect any of thosefile descriptors from the shell command line when you execute a Java program,then that redirected I/O is available to your Java applicati<strong>on</strong>—with noadditi<strong>on</strong>al work <strong>on</strong> your part.In the example above, if you have System.in all wrapped up into aBufferedReader from which your program is reading lines, then you can runthat program as:$ java MyCodeand it will read input as you type it <strong>on</strong> your keyboard. This may be how youtest your program, but when you put this program to its intended use, you maywant it to be able to read from a file. This you can do without any change tothe program—thanks to file descriptors, input streams, and redirecting input,for example:$ java MyCode < file2which will let the same Java program read from the file named file2 ratherthan from keyboard.Your Java program can also set the values of System.in, System.out,and System.err as it executes, to change their destinati<strong>on</strong>s.One comm<strong>on</strong> example is changing the destinati<strong>on</strong> of System.out, thetypical recipient of debugging or logging messages. Say you’ve created a class

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

Saved successfully!

Ooh no, something went wrong!