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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

ASCII format is the default and is the simplest to implement. This conversion can be<br />

accomplished merely by copying the input data to the console.<br />

Example 4.3. The FileDumper Program<br />

import java.io.*;<br />

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

public class FileDumper {<br />

public static final int ASC = 0;<br />

public static final int DEC = 1;<br />

public static final int HEX = 2;<br />

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

if (args.length < 1) {<br />

System.err.println("Usage: java FileDumper [-ahd] file1 file2...");<br />

return;<br />

}<br />

int firstArg = 0;<br />

int mode = ASC;<br />

if (args[0].startsWith("-")) {<br />

firstArg = 1;<br />

if (args[0].equals("-h")) mode = HEX;<br />

else if (args[0].equals("-d")) mode = DEC;<br />

}<br />

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

if (mode == ASC) dumpAscii(args[i]);<br />

else if (mode == HEX) dumpHex(args[i]);<br />

else if (mode == DEC) dumpDecimal(args[i]);<br />

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

System.out.println("\r\n--------------------------------------<br />

\r\n");<br />

}<br />

}<br />

}<br />

public static void dumpAscii(String filename) {<br />

}<br />

FileInputStream fin = null;<br />

try {<br />

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

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

}<br />

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

finally {<br />

try {<br />

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

}<br />

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

}<br />

57

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

Saved successfully!

Ooh no, something went wrong!