oop with java, david j. barnes input-output1 a complex issue in programming language design. the...
TRANSCRIPT
OOP with Java, David J. Barnes
Input-Output 1
Input-Output
• A complex issue in programming language design.
• The interface to the outside world.– Differences must be accommodated as
transparently as possible.– Character sets, end-of-line, path separators,
endian-issues.
• Readers, Writers and Streams.
OOP with Java, David J. Barnes
Input-Output 2
The java.io Package
• Classes that provide an insulation layer.– The File class hides file system differences– Reader and Writer classes perform mapping to
and from Unicode.– Stream classes deliver raw byte input.– Whole objects may be read and written easily.
OOP with Java, David J. Barnes
Input-Output 3
The File Class
• A File object represents an abstract pathname.– Represents both files and directories (folders).– Name, parent directory, size, permissions.– Constructor takes the file’s name:
•File info = new File("Letter.txt");
– No exception thrown if the file does not exist.
OOP with Java, David J. Barnes
Input-Output 4
Methods of the File ClassFile info = new File("Letter.txt");if(info.exists()){ System.out.println("Size of "+info.getName()+ " is "+info.length()); if(info.isDirectory()){ System.out.println("The file is a directory."); } if(info.canRead()){ System.out.println("The file is readable."); } if(info.canWrite()){ System.out.println("The file is writeable."); }}
OOP with Java, David J. Barnes
Input-Output 5
FileReader and FileWriter
• The two main classes for reading and writing text files.– A file is opened when its name is passed to
their constructors.– Files should be closed (via close) when
finished with.– Their read and write methods deal with char
and char[].
OOP with Java, David J. Barnes
Input-Output 6
Opening and Closing a Filetry{ // Try to open the file. FileReader inputFile = new FileReader(filename); // Process the file's contents. ... // Close the file now that it is finished with. inputFile.close();}catch(FileNotFoundException e){ System.out.println("Unable to open "+filename);}catch(IOException e){ // The file could not be read or closed. System.out.println("Unable to process "+filename);}
OOP with Java, David J. Barnes
Input-Output 7
Copying a Text Filevoid copyFile(FileReader inputFile, FileWriter outputFile) throws IOException { final int bufferSize = 1024; char[] buffer = new char[bufferSize]; // Read the first chunk of characters. int numberRead = inputFile.read(buffer); while(numberRead > 0){ // Write out what was read. outputFile.write(buffer,0,numberRead); numberRead = inputFile.read(buffer); } outputFile.flush();}
OOP with Java, David J. Barnes
Input-Output 8
Reading Single Charactersvoid copyFile(FileReader inputFile,FileWriter outputFile){ try{ // Read the first character. int nextChar = inputFile.read(); // Have we reached the end of file? while(nextChar != -1){ outputFile.write(nextChar); // Read the next character. nextChar = inputFile.read(); } outputFile.flush(); } catch(IOException e){ System.out.println("Unable to copy a file."); }}
OOP with Java, David J. Barnes
Input-Output 9
Input-Output Bottlenecks
• Input-output is generally a slow process.– Disk and network access are often involved.
• A single large read/write probably takes little more time than a small read/write.
• Buffered classes bundle multiple read/write operations into fewer.– Read more than is required.– Delay writing until more is ready.
OOP with Java, David J. Barnes
Input-Output 10
Buffered Reader and Writerstry{ FileReader in = new FileReader(infile); BufferedReader reader = new BufferedReader(in); FileWriter out = new FileWriter(outfile); BufferedWriter writer = new BufferedWriter(out); ... reader.close(); writer.close();}catch(FileNotFoundException e){ System.out.println(e.getMessage());}catch(IOException e){ System.out.println(e.getMessage());}
OOP with Java, David J. Barnes
Input-Output 11
Line-by-Line Copying
BufferedReader reader = new BufferedReader(...);// Read the first line.String line = reader.readLine();// null returned on EOF.while(line != null){ // Write the whole line. writer.write(line); // Add the newline character. writer.newLine(); // Read the next line. line = reader.readLine();}
OOP with Java, David J. Barnes
Input-Output 12
The Stream Classes
• Several classes that deliver input as a stream of raw bytes, or write raw bytes.– BufferedInputStream, DataInputStream, FileInputStream.
– BufferedOutputStream, DataOutputStream,– FileOutputStream.
• Their read and write methods take byte[] rather than char[] arguments.
OOP with Java, David J. Barnes
Input-Output 13
Stream Readers and Writers• InputStreamReader and Output-StreamWriter bridge the divide.
• Different file encodings supported.
• Constructed from an appropriate Stream.– Read/Write operations are delegated.– Read/Write operations take char arguments.
• Used to wrap System.in– new InputStreamReader(System.in)
OOP with Java, David J. Barnes
Input-Output 14
Reading and Writing Objects• We often want objects to be persistent
across program runs.– Defining storage methods on a per-class basis is
inefficient and error-prone.– An agreed binary format is necessary for
portability.– Version control is important.
• Serialization: ObjectInputStream and ObjectOutputStream.
OOP with Java, David J. Barnes
Input-Output 15
The StreamTokenizer Class
• Constructed from a Reader, to which it delegates its input requests.
• Returns tokens: multi-character numbers or strings.– TT_NUMBER, TT_WORD, TT_EOF.
• Really designed with programming language translation in mind.
OOP with Java, David J. Barnes
Input-Output 16
The StringTokenizer Class
• Defined in the java.util package.
• Splits strings into separate String tokens.– Delimiter characters are user settable
(whitespace by default).– Will also return delimiters if required.
• Simple interface– public boolean hasMoreTokens()– public String nextToken()
OOP with Java, David J. Barnes
Input-Output 17
Finding Words
String line = in.readLine();while(line != null){ StringTokenizer tokenizer = new StringTokenizer(line,",;:.\"' \t"); while(tokenizer.hasMoreTokens()){ String word = tokenizer.nextToken(); // Print the next word. System.out.println(word); } line = in.readLine();}
OOP with Java, David J. Barnes
Input-Output 18
Review
• Input-Output is usually difficult to perform in a platform-independent way.
• The java.io package provides the required independence.
• The File class supplies details of external files.
• Use Reader and Writer classes for text files.
OOP with Java, David J. Barnes
Input-Output 19
Review (cont.)
• Use Buffered classes for input-output efficiency.
• Use Stream classes when access to binary data is required.
• Stream Reader/Writer classes form a bridge between streams and readers and writers.
• StringTokenizer is useful for breaking up textual input.