Unformatted text preview:

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 StreamsStreamsAnnouncementsAnnouncementsOnly responsible for 16.1,16.3Only responsible for 16.1,16.3Other 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 GoalsTo 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 FilesText files – files containing plain textText files – files containing plain textCreated 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 ScannerScannerAssociate with files instead of Associate with files instead of System.inSystem.inAll input classes, except Scanner, are in All input classes, except Scanner, are in java.iojava.ioimport java.io.*;import java.io.*;Review: ScannerReview: ScannerTwo ways to use scanner Two ways to use scanner  two two constructorsconstructorsFirst 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 programExample: Example: System.inSystem.inRecall – 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 InputFirst 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?ExceptionsExceptionsnextInt()nextInt() throws throws InputMismatchExceptionInputMismatchExceptionparseInt()parseInt() throws throws NumberFormatExceptionNumberFormatExceptionOptimal useOptimal usenextInt()nextInt() when multiple information on when multiple information on one lineone linenextLine() + parseInt()nextLine() + parseInt() when one when one number per linenumber per lineReadingReadingTo read from a disk file, construct a To read from a disk file, construct a FileReaderFileReaderThen, 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);AlternativeAlternativeUse 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 knowknownext, nextLine, nextIntnext, nextLine, nextInt, etc., etc.Reads the information from the file Reads the information from the file instead of consoleinstead of consoleFile ClassFile Classjava.io.Filejava.io.Fileassociated with actual file on hard driveassociated with actual file on hard driveused to check file's statusused to check file's statusConstructorsConstructorsFile(<full path>)File(<full path>), , File(<path>, <filename>)File(<path>, <filename>) Predicate MethodsPredicate Methodsexists()exists()canRead()canRead(), , canWrite()canWrite()isFile()isFile(), , isDirectory()isDirectory()Writing To FileWriting To FileWe will use a We will use a PrintWriterPrintWriter object to object to write to a filewrite to a fileWhat 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 nameHow do we use a How do we use a PrintWriterPrintWriter object? object?Have we already seen one? Almost.Have we already seen one? Almost.PrintWriterPrintWriterThe 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 nowCan use either a filename or File objectCan use either


View Full Document

UW-Madison CS 302 - Files and Streams

Download Files and Streams
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Files and Streams and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Files and Streams 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?