Chapter 16 – Files and StreamsAnnouncementsChapter GoalsSlide 4Slide 516.1 Reading and Writing Text FilesReview: ScannerReview: Numerical InputWhat’s the difference?ReadingAlternativeWhat does this do?File ClassWriting To FilePrintWriterClosing FileWhy?File nameGetting it all to workJava Input ReviewSlide 21Slide 22Common ErrorBuffering gone badWhat to do?16.3 An Encryption ProgramCaesar CipherCaesar Cipher for alphabetic charactersModifications of OutputTokenizingWhyTokenizing in JavaString Tokenizing in JavaWhat if I want to read this file?Slide 35Slide 36Slide 37Java File OutputSlide 39to flush or not to flushOther Ways to Read/Write FilesChapter 16 – Chapter 16 – Files and Files and StreamsStreamsAnnouncementsAnnouncementsOnly responsible for 16.1,16.3Only responsible for 16.1,16.3Other sections “encouraged”Other sections “encouraged”Responsible for online supplements Responsible for online supplements for Exceptions and File I/O (see for Exceptions and File I/O (see syllabus)syllabus)Chapter GoalsChapter GoalsTo be able to read and write text To be able to read and write text files files To become familiar with the To become familiar with the concepts of text and binary formats concepts of text and binary formats To learn about encryption To learn about encryption To understand when to use To understand when to use sequential and random file accesssequential and random file accessMEMCPUHDDkeyboardmonitorterminalconsolestandard input streamstandardoutput streamStreamsStreamsWhat does information What does information travel across?travel across?MEMCPUHDDkeyboardmonitorterminalconsolestandard input streamstandardoutput streamfileinput streamLOADREADfile output streamSAVEWRITEStreamsStreamsfilesWhat does What does information travel information travel across?across?16.1 Reading and Writing 16.1 Reading and Writing Text FilesText FilesText files – files containing plain textText files – files containing plain textCreated with editors such as notepad, etc.Created with editors such as notepad, etc.Simplest way to learn it so extend our Simplest way to learn it so extend our use of use of ScannerScannerAssociate with files instead of Associate with files instead of System.inSystem.inAll input classes, except Scanner, are in All input classes, except Scanner, are in java.iojava.ioimport java.io.*;import java.io.*;Review: ScannerReview: ScannerTwo ways to use scanner Two ways to use scanner two two constructorsconstructorsFirst constructors takes an object of First constructors takes an object of type type java.io.InputStreamjava.io.InputStream – stores – stores information about the connection information about the connection between an input device and the between an input device and the computer or programcomputer or programExample: Example: System.inSystem.inRecall – only associate one instance of Recall – only associate one instance of Scanner Scanner with with System.inSystem.in in your program in your programReview: Numerical InputReview: Numerical InputFirst way:First way:Use Use nextInt()nextInt()int number = scanner.nextInt();int number = scanner.nextInt();Second way:Second way:Use Use nextLine(), Integer.parseInt()nextLine(), Integer.parseInt()String input = scanner.nextLine();String input = scanner.nextLine();int number = Integer.parseInt(input);int number = Integer.parseInt(input);What’s the difference?What’s the difference?ExceptionsExceptionsnextInt()nextInt() throws throws InputMismatchExceptionInputMismatchExceptionparseInt()parseInt() throws throws NumberFormatExceptionNumberFormatExceptionOptimal useOptimal usenextInt()nextInt() when multiple information on when multiple information on one lineone linenextLine() + parseInt()nextLine() + parseInt() when one when one number per linenumber per lineReadingReadingTo read from a disk file, construct a To read from a disk file, construct a FileReaderFileReaderThen, use the Then, use the FileReaderFileReader to construct to construct a a ScannerScanner object object FileReader reader = new FileReader("input.txt"); FileReader reader = new FileReader("input.txt"); Scanner in = new Scanner(reader); Scanner in = new Scanner(reader);AlternativeAlternativeUse Use FileFile instead of instead of FileReader FileReader Has an exists( ) method we can call to Has an exists( ) method we can call to avoid FileNotFoundExceptionavoid FileNotFoundExceptionFile file = new File ("input.txt"); File file = new File ("input.txt"); Scanner in;Scanner in;if(file.exists()){if(file.exists()){in = new Scanner(file);in = new Scanner(file);} else {} else {//ask for another file//ask for another file}}What does this do?What does this do?Allows us to use methods we already Allows us to use methods we already knowknownext, nextLine, nextIntnext, nextLine, nextInt, etc., etc.Reads the information from the file Reads the information from the file instead of consoleinstead of consoleFile ClassFile Classjava.io.Filejava.io.Fileassociated with actual file on hard driveassociated with actual file on hard driveused to check file's statusused to check file's statusConstructorsConstructorsFile(<full path>)File(<full path>), , File(<path>, <filename>)File(<path>, <filename>) Predicate MethodsPredicate Methodsexists()exists()canRead()canRead(), , canWrite()canWrite()isFile()isFile(), , isDirectory()isDirectory()Writing To FileWriting To FileWe will use a We will use a PrintWriterPrintWriter object to object to write to a filewrite to a fileWhat if file already exists? What if file already exists? Empty file Empty file (delete whatever is there)(delete whatever is there)Doesn’t exist? Doesn’t exist? Create empty file with Create empty file with that namethat nameHow do we use a How do we use a PrintWriterPrintWriter object? object?Have we already seen one? Almost.Have we already seen one? Almost.PrintWriterPrintWriterThe The outout field of field of SystemSystem is a is a PrintStream PrintStream object object associated with the console. associated with the console. PrintWriterPrintWriter is a is a similar class optimized for writing characters.similar class optimized for writing characters.We will associate our We will associate our PrintWriterPrintWriter with a file now with a file nowCan use either a filename or File objectCan use either
View Full Document