Presentation is loading. Please wait.

Presentation is loading. Please wait.

©SoftMoore ConsultingSlide 1 Appendix G: Java Input/Output.

Similar presentations


Presentation on theme: "©SoftMoore ConsultingSlide 1 Appendix G: Java Input/Output."— Presentation transcript:

1 ©SoftMoore ConsultingSlide 1 Appendix G: Java Input/Output

2 ©SoftMoore ConsultingSlide 2 The March of Progress (Cay Horstmann) 1980: C printf("%10.2f", x); 1988: C++ cout << setw(10) << setprecision(2) << showpoint << x; 1996: Java java.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: Java System.out.printf("%10.2f", x);

3 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 Example System.out.printf("The answer is %10.2f", x); ©SoftMoore ConsultingSlide 3

4 ©SoftMoore ConsultingSlide 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 5 BufferedReader br = new BufferedReader (new InputStreamReader(System.in); String str = br.readline(); int n = Integer.parseInt(str); Example: Using the Scanner class Scanner s = new Scanner(System.in); int n = s.nextInt();

5 ©SoftMoore ConsultingSlide 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 Example File a = new File("/usr/local/bin/foo");

6 ©SoftMoore ConsultingSlide 6 File Names Some information depends on VM Start of path Physical drives Slashes File 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!)

7 ©SoftMoore ConsultingSlide 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)

8 ©SoftMoore ConsultingSlide 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()

9 ©SoftMoore ConsultingSlide 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

10 ©SoftMoore ConsultingSlide 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)

11 ©SoftMoore ConsultingSlide 11 Reading and Writing Files To read/write files on a disk: FileInputStream FileOutputStream FileReader FileWriter Provided Constructors class(File) class(String) class(FileDescriptor) class(String, boolean)- [output only]

12 ©SoftMoore ConsultingSlide 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()

13 ©SoftMoore ConsultingSlide 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();

14 ©SoftMoore ConsultingSlide 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!

15 ©SoftMoore ConsultingSlide 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!

16 ©SoftMoore ConsultingSlide 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 one byte = bis.read(); // returns next byte bis.close(); // always close outermost!

17 ©SoftMoore ConsultingSlide 17 Reading Lines of Text BufferedReader provides method readLine() –reads all characters up to a “newline” –returns String containing those characters without newline Example BufferedReader br = new BufferedReader(new FileReader(args[0])); String line = null; while((line = br.readLine()) != null) System.out.println(line); br.close(); // always close outermost!

18 ©SoftMoore ConsultingSlide 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

19 ©SoftMoore ConsultingSlide 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 Example PrintStream ps = new PrintStream(new FileOuputStream("foo.txt")); ps.println("Hello!"); ps.flush(); ps.println("How are you?"); ps.flush();

20 ©SoftMoore ConsultingSlide 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 Example PrintStream ps = new PrintStream(new FileOutputStream("foo.txt"), true); ps.println("Hello!"); ps.println("How are you?");

21 ©SoftMoore ConsultingSlide 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

22 ©SoftMoore ConsultingSlide 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.

23 ©SoftMoore ConsultingSlide 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

24 ©SoftMoore ConsultingSlide 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

25 ©SoftMoore ConsultingSlide 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.

26 ©SoftMoore ConsultingSlide 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

27 ©SoftMoore ConsultingSlide 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.txt LittleMissMuffet.txt littleMissMuffet.TXT Recommendations –Use the same case always. –If possible, use all-lower case. –Never intentionally use same name with different cases.

28 ©SoftMoore ConsultingSlide 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

29 ©SoftMoore ConsultingSlide 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.

30 ©SoftMoore ConsultingSlide 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.

31 ©SoftMoore ConsultingSlide 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

32 ©SoftMoore ConsultingSlide 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?

33 ©SoftMoore ConsultingSlide 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 }

34 ©SoftMoore ConsultingSlide 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); }

35 ©SoftMoore ConsultingSlide 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) {} }

36 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 ConsultingSlide 36


Download ppt "©SoftMoore ConsultingSlide 1 Appendix G: Java Input/Output."

Similar presentations


Ads by Google