Tài liệu Bài giảng An Introduction to Computer Science Using Java - Chapter 15 Text Processing and File Input/Output: Chapter 15Text Processing andFile Input/OutputLecture Slides to AccompanyAn Introduction to Computer Science Using Java (2nd Edition)byS.N. Kamin, D. Mickunas, E. ReingoldChapter PreviewIn this chapter we will:describe the java.io packageintroduce the Java StringBuffer classshow how files can be read and writtendiscuss how to handle file input and output exceptionsdemonstrate how to perform console input and output StringsJava provides a number of methods for operating on String objectsString objects are immutableImmutable objects cannot be changed once they are createdStringBufferJava provides a mutable staring class called StringBuffer that allows strings to grow dynamically during program executionSeveral StringBuffer methods are the same as those found in StringTo convert between String objects and StringBuffer objects Java provides constructors for each classThe StringBuffer class also contains a ToString method to allow easier outputSequential FilesFiles are stored are stored o...
20 trang |
Chia sẻ: honghanh66 | Lượt xem: 1013 | Lượt tải: 0
Bạn đang xem nội dung tài liệu Bài giảng An Introduction to Computer Science Using Java - Chapter 15 Text Processing and File Input/Output, để tải tài liệu về máy bạn click vào nút DOWNLOAD ở trên
Chapter 15Text Processing andFile Input/OutputLecture Slides to AccompanyAn Introduction to Computer Science Using Java (2nd Edition)byS.N. Kamin, D. Mickunas, E. ReingoldChapter PreviewIn this chapter we will:describe the java.io packageintroduce the Java StringBuffer classshow how files can be read and writtendiscuss how to handle file input and output exceptionsdemonstrate how to perform console input and output StringsJava provides a number of methods for operating on String objectsString objects are immutableImmutable objects cannot be changed once they are createdStringBufferJava provides a mutable staring class called StringBuffer that allows strings to grow dynamically during program executionSeveral StringBuffer methods are the same as those found in StringTo convert between String objects and StringBuffer objects Java provides constructors for each classThe StringBuffer class also contains a ToString method to allow easier outputSequential FilesFiles are stored are stored on disksIn this section we will assume that files consist of multiple lines composed of charactersEach line ends with an end of line characterThe file itself may have an end of file characterProgrammers often need to read or write files stored on disksFile InputJava classes that support file input are found in the java.io packageFileReader allows us to open a file for readingBufferedReader is a wrapper class that provides methods that allow us to treat the file as a stream of charactersincreases the efficiency of readingallows line-oriented readingWrapper ClassesClass W is said to wrap class Y if:Y is a concrete (not abstract) classW’s constructor takes Y as an argument and stores a local copy of YW reimplements all of Y’s methodsA wrapper can wrap a class and be the subclass of another class at the same timeBuffered InputWe can make a file available for reading one character at a time by using FileReader fr = FileReader(filename);We can read the file more efficiently by reading a block of characters at a time, this is called buffering the readTo perform a buffered read we use this BufferedReader br = new BufferedReader( new FileReader(filename));Input Example – Part 1import CSLib.*;import java.io.*;public class Copy { // Copy file to an OutputBox private FileBuffer fr; private BufferedReader br; public Copy(String filename) throws IOException { // open local file given by filename br = new BufferedReader(new FileReader(filename)); } Input Example – Part 2 public void copy( ) throws IOException { OutputBox out = new OutputBox( ); int I; while (true) { i = br.read(); if (i == -1) // check for end of file return; out.print((char) i); // must have char to print } }}File OutputJava classes that support file output are found in the java.io packageFileWriter and BufferedReader provide methods to write a single character an array of characters a stringthe end of linePrintWriter is a wrapper class provided to convert several data type values to printable forms Writing to a FileTo make a file available for printingPrintWriter pr = new PrintWriter( new BufferedWriter( new FileWriter(filename)));PrintWriter has void methods print and println that behave the same way as they for OutputBox objectsMail Merge Application – part 1import java.io.*;public class MailMerge{ // mail merge application BufferedReader template, maillist; PrintWriter out; public void openFiles(String fn) throws Ioexception { template = new BufferedReader( new FileReader(fn + “.template”)); maillist = new BufferedReader( new FileReader(fn + “.list”)); out = new PrintWriter( new BufferedWriter( new FileReader(fn + “.out”))); }Mail Merge Application – part 2 private StringBuffer readUpto(BufferedReader br, char delim) throws Ioexception { StringBuffer sb = new StringBuffer( ); int inputChar; while (true) { inputchar = br.read( ); if ((inputchar == -1) || (inputchar == delim)) return sb; sb.append((char) inputchar); } } private StringBuffer[] st = new StringBuffer[10];Mail Merge Application – part 3 private int readTemplate( ) throws Ioexception { int n; // Read the first portion of the template st[0] = readUpro(template, ‘%’); // If there is there is an ‘%’ as the first char // read the rest of the template for (n = 1; n < 10; n++) { st{n] = readUpto(template, ‘%’); if (st[n].length() == 0) // might be empty return n; } return n; }Mail Merge Application – part 4 public void merge( ) throws Ioexception { Stringbuffer sm; in n = readTemplate(); // Read the first field sm = readUpto(mailList, ‘#’); while (true) { // if no more fields if (sm.length() == 0)return; out.print(st[0]); // interleave template portions and fields for (int i = 1; i < n; i++) { mailList.read( ); // get past new line out.print(sm); // print field out.print(st[i]); // print next template sm = readUpto(mailList, ‘#’); } out.println(“--------------------------------”); }Mail Merge Application – part 5 public void closeFiles( ) { out.close( ); }}A typical clientimport java.io.*;public class MailMergeClient { public static void main (String{] args) throws exception IOException { MailMerge mm = new MailMerge( ); mm.openFiles(args[0]); mm.merge( ); mm.closeFiles( );}}
Các file đính kèm theo tài liệu này:
- chapter15_0727.ppt