Download presentation
Presentation is loading. Please wait.
Published byDina Nelson Modified over 9 years ago
1
Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering
2
Copyright © 1999 - 2012 Curt Hill The Difficulty of File Design There are very many different approaches to file design in programming languages None have mastered it or all others would have copied them C++ has two completely different approaches –IOStream use > –StdIO use printf and scanf Random access files are particularly operating system sensitive
3
Copyright © 1999 - 2012 Curt Hill One example: end of file Three or more approaches Error exit routine –FORTRAN –COBOL Pre-check –Pascal Post-check –C++
4
Copyright © 1999 - 2012 Curt Hill External Data What does data come from? or Where does it go? –A file, such as on disk –Console –Network connection –Pipe –String –Array of bytes –Two or more of above collected together The problem is making these look similar
5
Copyright © 1999 - 2012 Curt Hill Formatting How is the data modified from source to destination? No formatting –R aw bytes or characters Collecting –An integer stored as 4 binary bytes Formatting based on desired type –Digit characters transformed into an integer
6
Copyright © 1999 - 2012 Curt Hill Direction Files may be processed in several directions –Input –Output Append –Input and Output
7
Copyright © 1999 - 2012 Curt Hill Organization and Access Organization –Sequential May be buffered for efficiency –Random Access Direct Indexed Access –How it is processed –Must be no stronger than organization All are OS dependent
8
Copyright © 1999 - 2012 Curt Hill Classes There are many classes that capture these capabilities They are then cascaded to give the desired result The beginnings are InputStream and OutputStream which are abstract base classes To be useful they are subclassed These are in java.io.*
9
Copyright © 1999 - 2012 Curt Hill InputStream Defines the following functions: –int available() –void close() –void mark(int) –boolean marksupported() –int read(byte []) –int read(byte [], int offset, int len) –void reset() –long skip(long)
10
Copyright © 1999 - 2012 Curt Hill InputStream Descendents AudioInputStream ByteArrayInputStream FileInputStream –Constructor takes a file name string FilterInputStream ObjectInputStream PipedInputStream SequenceInputStream StringBufferInputStream There are also other abstract classes
11
The Readers The InputStream descendents do not have the convenient methods for processing input that is people readable The read methods generally only reads a byte –This is one half of a character There are several Reader objects that do have nicer methods Copyright © 1999 - 2012 Curt Hill
12
Reader This is generally not used, but is the ancestor of several that are quite handy The read method of this object (and descendents) reads a character, not a byte It has several handy descendents: –InputStreamReader –BufferedReader Copyright © 1999 - 2012 Curt Hill
13
Readers InputStreamReader adds the functionality of reading from an InputStream –Such as a disk file BufferedReader adds two things: –Buffering –readLine method that reads a whole line and returns a string Copyright © 1999 - 2012 Curt Hill
14
End of File Each class has the option to handle EOF differently The DataInputStream does throw an EOFException InputStreamReader has a read which returns an int –If EOF it returns a -1 It also has a ready method which returns true should there be somthing left to read
15
Copyright © 1999 - 2012 Curt Hill OutputStream Another abstract base class Defines the following functions: –void close() –void flush() –void write(byte []) –void write(byte [], int offset, int len)
16
Copyright © 1999 - 2012 Curt Hill Instantiable Output Streams ByteArrayOutputStream FileOutputStream PipeOutputStream FilterOutputStream
17
Copyright © 1999 - 2012 Curt Hill Exceptions InputStream and OutputStream objects throw various kinds of IOExceptions Constructors using file names usually throw FileNotFoundException Others I/O throw IOException Most operations need to be in try catch
18
Copyright © 1999 - 2012 Curt Hill Filters FilterInputStream and FilterOutputStream are also abstract classes Designed to be the super classes of all formatting classes or any other added functionality Subclasses include: BufferXXXStream, DataXXXStream and others Provide the same functionality as InputStreams or OutputStreams
19
Copyright © 1999 - 2012 Curt Hill Buffering Buffering separates logical reads or writes from physical reads or writes Devised in the 1950s to save space on tape Today we do it to make access faster Reading an entire track is only slightly slower than reading a single sector
20
Copyright © 1999 - 2012 Curt Hill Java Buffered Classes Two buffering classes: –BufferedInputStream which takes an InputStream in its constructor –BufferedOutputStream which takes an OutputStream in its constructor They provide all the same functionality as Stream but add buffering
21
Copyright © 1999 - 2012 Curt Hill Output formatting PrintStream is a subclass of FilterOutputStream Constructor takes an OutputStream Offers the print and println functions with many overloads –All the primitives –Object (uses String.valueOf) –String Handles its own exceptions so try catch is only needed for Opening
22
Copyright © 1999 - 2012 Curt Hill print and println These are methods which are defined in PrintStream They format variables and output them They are overloaded to take several different kinds of arguments They will only take one argument each –println may have no arguments as well
23
Copyright © 1999 - 2012 Curt Hill How the Classes Fit P OutputStream Application PrintStream BufferedOutputStream
24
Copyright © 1999 - 2012 Curt Hill Example Code import java.io.*; PrintStream f; try { f = new PrintStream( new BufferedOutputStream( new FileOutputStream( "junk.out"))); } catch (FileNotFoundException e) {error stuff}; f.print("Double "); f.println(d);
25
Copyright © 1999 - 2012 Curt Hill Discussion Only the creation needs to be protected by try catch PrintStream handles all the errors of writing itself The print and println methods are similar to those used by System.out
26
Copyright © 1999 - 2012 Curt Hill PrintWriter Similar to PrintStream –Not derived from PrintStream –All the same methods Constructor takes an OutputStream checkError returns whether an error occurred
27
Copyright © 1999 - 2012 Curt Hill Console Redirection The JVM has three standard files like C –Standard output System.out –Standard error System.err –Standard input System.in Each of these may be redirected to a file or processed by a program
28
Copyright © 1999 - 2012 Curt Hill Redirection Usually done for the execution of an existing program Three steps –Start program –Redirect files –Process these files
29
Copyright © 1999 - 2012 Curt Hill Starting a program Uses the Runtime static object Runtime rt = Runtime.getRuntime(); Now start the program Process proc = rt.exec(cmd,environment,dir); Cmd is an array of string Environment is an array of strings Dir is string
30
Copyright © 1999 - 2012 Curt Hill Standard files of a process Use a process method to get the output file Three Process methods are: –OutputStream getOutputStream(); Connects to input –InputStream getErrorStream(); Connects to error –InputStream getInputStream(); Connects to output
31
Copyright © 1999 - 2012 Curt Hill Capture the file Use this as file: PrintWriter ps = new PrintWriter(proc.getOutputStr eam()); Any println to this file is piped to the process input file
32
Copyright © 1999 - 2012 Curt Hill File output PrintStream is for people readable text What if the data is to be written to a file and then later read back in? No formatting is needed, instead writing in binary Yet it must be reversible and machine independent Uses DataOutputStream
33
Copyright © 1999 - 2012 Curt Hill DataOutputStream Subclass of FilterInputStream Constructor takes an OutputStream New functions are: –void writeFloat(float) –void writeInt(int) –void writeBytes(String) –void writeChars(String) There is no writeString
34
Copyright © 1999 - 2012 Curt Hill Input formatting DataInputStream is a subclass of FilterInputStream Reads in what a DataOutputStream wrote Constructor takes an InputStream Provides functions for reading the various types: –byte readByte() –double readDouble() No read string
35
Copyright © 1999 - 2012 Curt Hill GUI Swing has a JFileChooser –Similar to common dialog Open box Allows user to select a file at runtime The getSelectedFile returns a File The File getCanonicalPath is the file name and directory as a String Filters may also be implemented
36
Copyright © 1999 - 2012 Curt Hill JFileChooser
37
Copyright © 1999 - 2012 Curt Hill JFileChooser Methods JFileChooser() –Default constructor int showOpenDialog(Component) –Component is the owning window –Usually this which points at owning container –Owning container is usually a JFrame or JDialogue –Cannot be an applet –Returns indicator of user action
38
Copyright © 1999 - 2012 Curt Hill JFileChooser ShowOpenDialog Result The returned integer is one of several defined constants in JFileChooser JFileChooser.CANCEL_OPTION JFileChooser.APPROVE_OPTION JFileChooser.ERROR_OPTION The display of the dialog box does not touch any file or get any file class ready for I/O
39
Copyright © 1999 - 2012 Curt Hill Obtaining file name If the JFileChooser.APPROVE_OPTION is returned the user selected a file This may be obtained using the getSelectedFile method This returns a File object which contains information about the file We obtain name from this object among many other things
40
Copyright © 1999 - 2012 Curt Hill File Object Allows us to do things with a file on disk String getName() String getPath() boolean exists() boolean canRead() boolean canWrite() boolean delete()
41
Copyright © 1999 - 2012 Curt Hill Filters A file name filter restricts what files will be shown For example Word typically shows document files –Files ending in.doc JFileChooser may set one or more filters –setFileFilter(FileFilter) –FileFilter is an abstract class
42
Copyright © 1999 - 2012 Curt Hill JFileChooser Options Many options void setMultiSelectionEnabled(boolean) –Determines if one or many files may be selected void setFileView(FileView) –Icon or text display void setCurrentDirectory(File) –JFileChooser may change directories –This is the starting one –Defaults to current directory
43
Copyright © 1999 - 2012 Curt Hill Example 1 - Opening JFileChooser jfc = new JFileChooser(); int res = jfc.showOpenDialog(jFrame); if(res == JFileChooser.APPROVE_OPTION){ // Open the file BufferedReader infile; try{ infile = new BufferedReader( new InputStreamReader( new FileInputStream( jfc.getSelectedFile().getPath()))); } // end of try catch(FileNotFoundException fnfe){ outputArea.append( "This file does not exist."); return; }
44
Copyright © 1999 - 2012 Curt Hill Example 2 - Reading // Read until EOF and display try{ while(infile.ready()){ String s = infile.readLine(); outputArea.append(s); outputArea.append("\n"); } // while } // try catch(IOException exc){ System.out.println("Got an IOexception."); }
45
What about conversion? Converting a string of characters into an integer has mostly been left out of tradional Java Readers and Streams The way to do this is: –Read whole lines –Chop into pieces based on white space –Use Integer.parseInt (or similar) to convert to needed types In Java 5 the Scanner object was introduced Copyright © 1999 - 2012 Curt Hill
46
Scanner A Scanner may be constructed using either a File or InputStream –A File may be obtained from JFileChooser The scanner by default uses whitespace as the delimiter between tokens It has a series of hasNextXXX and nextXXX methods Copyright © 1999 - 2012 Curt Hill
47
hasNext methods Returns a boolean True if the item is the next token So: hasNextInt() is true if the next token can be interpreted as an integer Most of the types have one: –hasNextDouble –hasNextFloat –hasNextLine Copyright © 1999 - 2012 Curt Hill
48
next Methods Reads and returns the next item Example: int j = sc.nextInt(); One for most types: –nextBoolean –nextDouble –nextLine Copyright © 1999 - 2012 Curt Hill
49
Scanner Exceptions The hasNextXXX will throw the IllegalStateException if the scanner is closed The nextXXX will throw: –InputMismatchException if the item does not conform to specifications –NoSuchElementException if the Scanner has no input left –IllegalStateException if the scanner is closed Copyright © 1999 - 2012 Curt Hill
50
Text files Text files in any Microsoft Operating System always end a line with two characters –A carriage return followed by a line feed –Both are control characters UNIX based systems use only a line feed This may change how the file is processed on different systems
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.