©SoftMoore Consulting Slide 1
Appendix G:Java Input/Output
©SoftMoore Consulting Slide 2
The March of Progress(Cay Horstmann)
• 1980: Cprintf("%10.2f", x);
• 1988: C++cout << setw(10) << setprecision(2) << showpoint << x;
• 1996: Javajava.text.NumberFormat formatter = java.text.NumberFormat.getNumberInstance();formatter.setMinimumFractionDigits(2);formatter.setMaximumFractionDigits(2);String s = formatter.format(x);for (int i = s.length(); i < 10; i++) System.out.print(' ');System.out.print(s);
• 2004: JavaSystem.out.printf("%10.2f", x);
The printf() Method
• Java 5 (2004) added a printf() method to classes PrintStream and PrintWriter. The printf() method in Java is used in a manner similar to the printf() function in C.
• Each printf() method has at least two arguments– format string, which may contain fixed text and one or more
embedded format specifiers– a variable number of arguments whose values are printed
according to the format specifiers
• ExampleSystem.out.printf("The answer is %10.2f", x);
©SoftMoore Consulting Slide 3
©SoftMoore Consulting Slide 4
Simplified Input: Class Scanner
• In addition to the printf() method for output, Java 5 also provides the java.util.Scanner class to simplify input.
• Example: Before Java 5BufferedReader br = new BufferedReader (new InputStreamReader(System.in);String str = br.readline();int n = Integer.parseInt(str);
• Example: Using the Scanner classScanner s = new Scanner(System.in);int n = s.nextInt();
©SoftMoore Consulting Slide 5
The File Class
• Abstract file name
• Not an actual file!
• Helps deal with platform differences– methods to manipulate name– rename/delete files– create directories– list directory contents
• ExampleFile a = new File("/usr/local/bin/foo");
©SoftMoore Consulting Slide 6
File Names
Some information depends on VM
• Start of path
• Physical drives
• SlashesFile b = new File("bin/foo");
• Example (Windows file names)File c = new File("c:\\windows\\system\\foo.gif");File d = new File("system\\foo.gif");
(Note the double backslashes!)
©SoftMoore Consulting Slide 7
Files Relative to Files
Can pass a File to the constructor as parent directory File g = new File("/windows/system"); File h = new File(g, "foo.gif"); File i = new File("/windows/system", "foo.gif");
(h and i refer to the same file)
©SoftMoore Consulting Slide 8
Selected File Methods
boolean isDirectory() long lastModified() long length()
int compareTo(File) String getName() String getParent() File getParentFile() String getPath() URL toURL()
boolean createNewFile() boolean delete() boolean mkdir() boolean renameTo(File)
String[] list() File[] listFiles()
©SoftMoore Consulting Slide 9
Unicode
• In Java, strings are two-byte Unicode characters
• Unicode - standard that represents many worldwide characters in two bytes
• Unicode chars 0-127 are ASCII– Other “pages” represent other character sets– Different languages– Dingbats– Currency symbols– Mathematical symbols– … and many others
©SoftMoore Consulting Slide 10
Text Translation
• Text I/O classes translate native chars to/from Unicode
• I/O package provides "default mapping"
• Reading text: I/O classes translate from native to Unicode
• Writing text: I/O classes translate from Unicode to native
• Text I/O versus binary I/O– Reader and Writer classes handle text I/O (character
translation performed)– InputStream and OutputStream classes handle binary I/O
(bytes read/written as is)
©SoftMoore Consulting Slide 11
Reading and Writing Files
• To read/write files on a disk:FileInputStreamFileOutputStreamFileReaderFileWriter
• Provided Constructorsclass(File)class(String)class(FileDescriptor)class(String, boolean)- [output only]
©SoftMoore Consulting Slide 12
File Copy Example
FileInputStream inFile = new FileInputStream(args[0]);FileOutputStream outFile = new FileOutputStream(args[1]);
int byteRead;
while((byteRead = inFile.read()) != -1) outFile.write(byteRead);
inFile.close();outFile.close();
• Slow implementation!– reading/writing single character at a time– could be really bad over a network connection
• Can provide simple buffering using byte[] forms of read() and write()
©SoftMoore Consulting Slide 13
Buffered File Copy
FileInputStream inFile = new FileInputStream(args[0]); FileOutputStream outFile = new FileOutputStream(args[1]); byte[] buffer = new byte[1024];int i; while((i = inFile.read(buffer)) > 0) outFile.write(buffer, 0, i); inFile.close();outFile.close();
©SoftMoore Consulting Slide 14
Common I/O Filters
I/O package comes with several useful filters
• buffering to make I/O more efficient
• encoding primitive types
• writing the state of entire objects
• compressing I/O
• and many more!
©SoftMoore Consulting Slide 15
Buffering
• Writing a single byte or character at a time is inefficient
• Better to write a block of bytes or chars in a single write()
• java.io includes: BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter
• You should almost always use these!
©SoftMoore Consulting Slide 16
Buffering example
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("a.bin"));
int byte = bis.read(); // reads a block of bytes from // a.bin and returns onebyte = bis.read(); // returns next bytebyte = bis.read(); // returns next byte
bis.close(); // always close outermost!
©SoftMoore Consulting Slide 17
Reading Lines of Text
• BufferedReader provides method readLine()– reads all characters up to a “newline”– returns String containing those characters without newline
• ExampleBufferedReader br = new BufferedReader(new FileReader(args[0]));
String line = null;
while((line = br.readLine()) != null) System.out.println(line);
br.close(); // always close outermost!
©SoftMoore Consulting Slide 18
Print Streams
• PrintStream and PrintWriter provide primitive/object value output
• System.out and System.err are two predefined instances of PrintStream
• print() and println() exist for each primitive type and for Object– print() converts its argument to a String, then writes it to its
delegate– println() does the same, but follows with the appropriate
newline
©SoftMoore Consulting Slide 19
Flushing and PrintStreams
• Common use of PrintStream is communicating status to user– Flushing output becomes significant!– When you print output, you need to flush periodically
• ExamplePrintStream ps = new PrintStream(new FileOuputStream("foo.txt"));
ps.println("Hello!");ps.flush();
ps.println("How are you?");ps.flush();
©SoftMoore Consulting Slide 20
Automatic Flushing
• Flushing can be easy to forget
• PrintStream and PrintWriter can “autoflush”– disabled by default.– enabled by passing true to PrintStream or PrintWriter
constructor
• ExamplePrintStream ps = new PrintStream(new FileOutputStream("foo.txt"), true);
ps.println("Hello!");ps.println("How are you?");
©SoftMoore Consulting Slide 21
PrintStream and Text Output
• Note that PrintStream is commonly used for text output!– converts chars to appropriate binary on current platform– output is filtered to convert characters– allows backward compatibility with earlier JDK
• You should always use PrintWriter for non-System.out text output – it’s more efficient
©SoftMoore Consulting Slide 22
IO Exceptions and PrintStream
• PrintStream and PrintWriter do not throw exceptions!
• System.out and System.err are very heavily used. Exception handling would be painful.
• PrintStream and PrintWriter catch their own exceptions and set an error flag.
• If you using these for real output, call checkError() to see if an error has occurred.
©SoftMoore Consulting Slide 23
Primitive Data Input and Output
• You can store primitive types via PrintStream
• Reading these values requires parsing from String values! This is inefficient!
• Better way: write binary data to a file
©SoftMoore Consulting Slide 24
Writing Objects
• Writing object values – object serialization
• Uses interfaces ObjectInput and ObjectOutput– ObjectInputStream and ObjectOutputStream implement
these interfaces
• Interface Serializable “marks” a class to be written
• Serialization covered in the Object Serialization course module – no further coverage here
©SoftMoore Consulting Slide 25
Platform Specifics
• File systems vary greatly between operating systems– many “common concepts,” but implementations vary significantly – many “unique” features; e.g., UNIX's permission levels– Case-sensitive/insensitive– Characters allowed in file names– Many more
• I/O Package Helps, But Be Careful!– I/O is the easiest portability killer in applications.– Easy to create applications that work on your platform, but not
others.– Always think about portability issues when writing I/O code.
©SoftMoore Consulting Slide 26
Characters in File Names
• Each platform defines– valid file name characters– case significant or not– file name length
• Examples– asterisk ('*')– space (' ') (some platforms allow, others don't)
• For maximum portability, restrict file name characters – letters (A-Z and a-z)– numbers (0-9)– start file names with a letter
©SoftMoore Consulting Slide 27
File Name Case Sensitivity
• Unix is case sensitive,
• Windows is not.
• Other platforms differ as well.
• Do the following names refer to the same file?littleMissMuffet.txtLittleMissMuffet.txtlittleMissMuffet.TXT
• Recommendations– Use the same case always.– If possible, use all-lower case.– Never intentionally use same name with different cases.
©SoftMoore Consulting Slide 28
New-Line Characters
• Where does one “line” of text end and the next begin?
• Three general patterns: – "\n" the “Unix way”– "\r" the “Macintosh way”– "\r\n" the “DOS/Windows way”
• This is the easiest trap to fall into with I/O
©SoftMoore Consulting Slide 29
File Separator in Path Names
• Which character separates files/directories in path names?– Unix uses “/”– Windows uses “\” (which must be represented as “\\” in
strings.
• Recall that File “does the right thing” for slashes.
• Use system property file.separator for portability.
©SoftMoore Consulting Slide 30
Path and Class Path Sequence Separator
c:;c:\programs [Windows]/usr/local/bin:/bin [UNIX]
• Note semicolon (';') use in Windows sequence, colon (':') in UNIX sequence
• These are “path separation characters”(differ between platforms)
• Use system property path.separator for portability.
©SoftMoore Consulting Slide 31
Common I/O Exceptions
• IOException– General I/O exception– Superclass for all other I/O exceptions– Something undesirable happened while performing I/O
• EOFException– End of stream unexpectedly reached– Normally "end-of-file" is signaled by special value (e.g., 1)
• FileNotFoundException– File specified in constructor does not exist– Could also mean file being opened in wrong mode, trying to
open read-only file for write access
©SoftMoore Consulting Slide 32
Closing Streams
Difficult I/O operation – several subtle problems
• Where to put close() call?
• How to deal with exceptions when opening filters?
• What if filter's close() throws exception?
©SoftMoore Consulting Slide 33
Correct Approach for Simple File Closing
FileReader r = null;try { r = new FileReader("somefile.txt"); // NOTE: No close()! }catch(IOException e) { // message … }finally { if (r != null) try { r.close(); } catch(Exception ignore) {} // couldn't close -- inform user if important }
©SoftMoore Consulting Slide 34
Using Finally to Copy Files Safely
public void copy(File f1, File f2) throws IOException { InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(f1)); out = new BufferedOutputStream(new FileOutputStream(f2)); int x;
while ((x = in.read()) != -1) out.write(x); }
©SoftMoore Consulting Slide 35
Using Finally to Copy Files Safely(continued)
finally { if (in != null) try { in.close(); } catch (Exception ignore) {}
if (out != null) try { out.close(); } catch (Exception ignore) {} } }
New I/O
• In version 1.4 (2002), Java introduced several “new I/O” capabilities in package java.nio, including– Character set encoders and decoders– Nonblocking I/O– Memory-mapped files– File locking
• Java 7 contains additional enhancements, including– class Path (enhancement of class File)– class FileSystem– class WatchService (file change notification)– file attributes
©SoftMoore Consulting Slide 36