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

bit pattern to a particular output stream. How that bit pattern is interpreted depends on what's<br />

connected to the other end of the stream.<br />

Example 2.1. The AsciiChart Program<br />

import java.io.*;<br />

public class AsciiChart {<br />

}<br />

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

for (int i = 32; i < 127; i++) {<br />

System.out.write(i);<br />

// break line after every eight characters.<br />

if (i % 8 == 7) System.out.write('\n');<br />

else System.out.write('\t');<br />

}<br />

System.out.write('\n');<br />

}<br />

Notice the use of the char literals '\t' and '\n'. The compiler converts these to the numbers<br />

9 and 10, respectively. When these numbers are written on the console, the console interprets<br />

those numbers as a tab and a linefeed, respectively. The same effect could have been achieved<br />

by writing the if clause like this:<br />

if (i % 8 == 7) System.out.write(10);<br />

else System.out.write(9);<br />

Here's the output:<br />

% java AsciiChart<br />

! " # $ % & '<br />

( ) * + , - . /<br />

0 1 2 3 4 5 6 7<br />

8 9 : ; < = > ?<br />

@ A B C D E F G<br />

H I J K L M N O<br />

P Q R S T U V W<br />

X Y Z [ \ ] ^ _<br />

` a b c d e f g<br />

h i j k l m n o<br />

p q r s t u v w<br />

x y z { | } ~<br />

%<br />

The write() method can throw an <strong>IO</strong>Exception, so you'll need to wrap most calls to this<br />

method in a try/catch block, or declare that your own method throws <strong>IO</strong>Exception. For<br />

example:<br />

try {<br />

for (int i = 32; i

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

Saved successfully!

Ooh no, something went wrong!