Download presentation
Presentation is loading. Please wait.
Published bySharlene Reed Modified over 8 years ago
1
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.
2
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.
3
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.
4
4 Methods of the File Class File 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."); }
5
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[].
6
6 Opening and Closing a File try{ // 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); }
7
7 Copying a Text File void 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(); }
8
8 Reading Single Characters void 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."); }
9
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.
10
10 Buffered Reader and Writers try{ 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()); }
11
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(); }
12
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.
13
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)
14
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.
15
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.
16
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()
17
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(); }
18
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.
19
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.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.