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 Outputpublic class ReadLineTest {public static void main(String[] args) {try {// create a BufferedReader so we can read a line at a timeBufferedReader br = new BufferedReader(new FileReader(args[0]));}}Using Print Streams// print the line number and the lineString line = null;int i = 0;while((line = br.readLine()) != null) {i++;System.out.println(i + ": " + line);}br.close(); // always close outermost filter!}catch(Exception e) {e.printStackTrace();}Later you will see that DataInputStream also provides a readLine() method.The readLine() in DataInputStream should never be used! Remember,"InputStream" means binary input!Classes PrintStream and PrintWriter provide convenient ways to write aString representation of primitive and object values. You've certainly used aPrintStream already; it's the class that provides the println() method, as inSystem.out.println(...).These classes provide print() and println() methods for each primitive typeand for Object. The print() method converts its argument to a String, thenwrites that String to its outputDelegate. The println() method does the samething print() does, but follows it with a newline character that is appropriate forthe current platform ('\n', '\r', or '\r\n').For primitive arguments, the String class' valueOf() method is invoked, passingthe argument to print() or println(). For Object arguments, the object'stoString() method is invoked to perform the translation.There are two well-known PrintStreams in the Java core API: System.out andSystem.err. These streams provide access to the "standard output" and"standard error output" for the current platform.Java Input and Output -24© 1996-2003 jGuru.com. All Rights Reserved.

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

Saved successfully!

Ooh no, something went wrong!