13.07.2015 Views

I/O Fundamentals

I/O Fundamentals

I/O Fundamentals

SHOW MORE
SHOW LESS
  • No tags were found...

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

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

Java Input and Output}System.out.println(b);// run our sample testpublic static void main(String[] args) {try {// create some test databyte[] bytes = {1,2,3,4,5,6,7,8,9};InputStream in = new ByteArrayInputStream(bytes);// pass it to the methodgo(in);// close the streamin.close();// now read from a filein = new FileInputStream("somebytes.bin");// pass it to the methodgo(in);}// close the streamin.close();}}// in case there was an I/O exception...catch(IOException e) {e.printStackTrace();}In this example, we can pass in a ByteArrayInputStream or aFileInputStream; go() doesn't care! (Note that we rearranged where theexception handling occurs to reduce the code required.)ByteArrayOutputStream works in a similar manner. You can write() bytes to abyte array as well.import java.io.*;public class Test1 {public static void go(OutputStream out) throws IOException {// read each byte and echo to the consolefor(int i = 0; i < 11; i++)out.write((byte)i);}// run our sample testpublic static void main(String[] args) {try {// create some test dataJava Input and Output -14© 1996-2003 jGuru.com. All Rights Reserved.

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

Saved successfully!

Ooh no, something went wrong!