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 OutputFileWriter writer = new FileWriter("smurf.out");writer.write("This is a test\n" +"followed by another line\n" +"and another");From years of using printf, many programmers are used to using "\n" wheneverthey need a new line in output. This is not the case in Java.In Java, you are simply writing characters to a file. Character "\n" is simplyanother character.If you run the above code on a UNIX platform, it will behave as expected. If youopen smurf.out in a text editor, you will seeThis is a testfollowed by another lineand anotherHowever, if you run the above code under Windows and open it in notepad, youwill see something likeThis is a test[]followed by another line[]and anotherwhere we use [] is a representation of a "bad character".To make it work on Windows, your code would need to look likewriter.write("This is a test\r\n" +"followed by another line\r\n" +"and another");but it would then be wrong on UNIX. Of course both solutions are incorrect onthe Macintosh.Fortunately, Java provides a few ways to represent the new-line symbolsuccessfully.• asking the VM to identify the platform, and writing a new-line sequence basedon that information• a system property named line.separator• a set of classes called PrintWriter and PrintStreamThe first option may sound tempting, but at best you'll anticipate the currentplatforms, and more platforms may be added. At worst, you may miss severalimportant platforms or write incorrect code for a certain platform.Java Input and Output -52© 1996-2003 jGuru.com. All Rights Reserved.

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

Saved successfully!

Ooh no, something went wrong!