13.07.2015 Views

I/O Fundamentals

I/O Fundamentals

I/O Fundamentals

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

Create successful ePaper yourself

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

Java Input and OutputOPERATOR: ++OPERATOR: +OPERATOR: ++VARIABLE: yVARIABLE: xOPERATOR: /=VARIABLE: yOPERATOR: +VARIABLE: zOPERATOR: +VARIABLE: qWe will discuss some other approaches to separating this input at the end of thismodule.Converting from Binary to Text I/OThere are some cases where you are presented a binary input or output streamand would like to process text over those streams. The Java core APIs defineclasses InputStreamReader and OutputStreamWriter to perform the necessarycharacter conversion.For example, the writeText() method in the following example is passed anOutputStream. To ensure proper character translation, we wrap theOutputStream in a OutputStreamWriter.import java.io.*;public class OutputStreamWriterTest {public static void main(String[] args) {try {FileOutputStream fos = new FileOutputStream("somefile.txt");writeIt(fos);fos.close();}catch(Exception e) {e.printStackTrace();}}}public static void writeIt(OutputStream out) {PrintWriter pw = new PrintWriter(new OutputStreamWriter(out));pw.println("Hello!");pw.println("How are you?");pw.flush(); // JUST FLUSH!!! Leave the file open}Note that in this particular example, we do not close the file in our writeIt()method. The file passed in is assumed to be open, and we want to leave it thatway when we exit. However, it is important to flush() the Writers so ourJava Input and Output -34© 1996-2003 jGuru.com. All Rights Reserved.

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

Saved successfully!

Ooh no, something went wrong!