COMP 110-001 Streams And File I/O - University Of Georgia

Transcription

COMP 110-001Streams and File I/OYi HongJune 10, 2015

Today§ Files, Directories, Path§ Streams§ Reading from a file§ Writing to a file

Why Use Files for I/O?§ RAM is not persistent§ Data in a file remains after programexecution, stored permanently

Working With Files§ The data stored in these persistent storageare normally in the form of files§ Have you tried to open a movie DVD in yourcomputer using file explorer?§ You will probably seesome folders andfiles like this:

Working With Files§ In short: We often need to write the data to files tostore it We often need to read the data from files§ We will cover some basics about files anddirectories in Windows / Linux & Mac OSfirst

Files and Directories§ Files are stored in directories orfolders in a tree structure§ A directory can contain oneor more files and/or directories§ The root directory in Windowsis the drive name ( C: or D: ,don’t miss the : )§ The root directory in Unix/Linux/MacOS is /

Files and Directories: Path to File§ A file is identified by its path through the filesystem, beginning from the root node Linux/Unix: e.g., /home/yihong/Music MacOS: e.g., /Users/yihong/Music Windows: e.g., C:\Users\yihong\Music§ The character used to separate the directorynames (also called the delimiter) isforward slash (/) in Linux/Unix/MacOS, andbackslash slash (\) in Windows.

Relative and Absolute Path§ A path is either relative or absolute An absolute path always contains the root element and thecomplete directory list required to locate the file e.g.: /Users/yihong/Music§ A relative path needs to be combined withanother path in order to access a file e.g. yihong/Music is a relative path Without more information, a program cannot reliably locatethe yihong/Music directory in the file system§ In java, when you write a relative path, it’srelative to the working directory

from the keyboard into your program. If an input stream is connected to a file,the data flows from the file into your program. Figure 10.1 illustrates some ofthese streams.*O BWB TUSFBNT BSF JNQMFNFOUFE BT PCKFDUT PG TQFDJBM TUSFBN DMBTTFT Objects of the class Scanner XIJDI XF IBWF CFFO VTJOH GPS LFZCPBSE JOQVU are input streams. The object System.out is an example of an output streamJava’s Input/Output Mechanism§ A stream is a flow of data into or out of a programFIGURE 10.1Input and Output StreamsInput streamOutput streamKeyboardMonitorInput streamOutput streamCompact discProgramHard disk§ Very complicated design based on “streams”§ Here, we focus on how to use input and out streams

REMEMBER Input and Output TerminologyText Files v.s. Binary Files5IF XPSE input NFBOT UIBU EBUB NPWFT JOUP ZPVS QSPHSBN OPU JOUP UIF GJMF 5IF XPSE output NFBOT UIBU EBUB NPWFT PVU PG ZPVS QSPHSBN OPU out of the file.§ Text file: a sequence of charactersFIGURE 10.2A Text File and a Binary File Containing the§ Binary file:packvalues into binary representationSameValuesA text file12345-40278A binary file12345 -40728.§ We only cover text file I/O in this course.

awill need to create and write to a text file. This class is the preferred one forwriting to a text file. It is in the package java.io, so we will need to begin ourprogram with an import statement. Actually, we will be using other classes aswell, so we will import them also, as you will see soon.Before we can write to a text file, we must connect it to an output stream.That is, we open the file. To do this, we need the name of the file as a string.The file has a name like out.txt that the operating system uses. We also mustEFDMBSF B WBSJBCMF UIBU XF XJMM VTF UP SFGFSFODF UIF TUSFBN BTTPDJBUFE XJUI UIF BDUVBM GJMF 5IJT WBSJBCMF JT DBMMFE UIF stream variable. Its data type in this caseis PrintWriter 8F PQFO B UFYU GJMF GPS PVUQVU CZ JOWPLJOH PrintWriter’sconstructor and passing it the file name as its argument. Since this action canthrow an exception, we must place the call to the constructor within a try block.The following statements will open the text file out.txt GPS PVUQVU Creating a Text File§ Opening a file connects it to a stream§ The class PrintWriter in the packagejava.io is for writing to a text fileString fileName "out.txt";//Could read file name from userPrintWriter outputStream null;try{outputStream new PrintWriter(fileName);}catch(FileNotFoundException e){System.out.println("Error opening the file " fileName);System.exit(0);}

Creating a Text File§ After we connect the file to the stream, wecan write data to it outputStream.println(“This is line 1.”); outputStream.println(“Here is line 2.”);§ Closing a file disconnects it from a stream outputStream.close();

3 a big fish in a small pond.read this file.Creating a Text FileRECAP Creating a Text File§ SYNTAXSyntax// Open the file PrintWriterOutput Stream Name null;try{Output Stream Name new PrintWriter(File Name);}catch(FileNotFoundException e){Statements Dealing With The ExceptionHAPTER 10 / Streams and File I/O}(continued)// Write the file using statements of either or both of the// following forms:Output Stream Name.println(.);Output Stream Name.print(.);// Close the fileOutput Stream Name.close();

Example

JUI UIF TPVSDF DPEF GPS UIJT CPPL BWBJMBCMF PO UIF 8FC Appending to a Text FileRECAP Opening a Text File for AppendingRECAP Opening a Text File for Appending:PV DBO DSFBUF B TUSFBN PG UIF DMBTT PrintWriter that appends data to§ Addingdatathe endof a filethat appends data totheendof an existingtexttofile.:PV DBO DSFBUF B TUSFBN PG UIF DMBTT PrintWriterthe end of an existing text file.§ SyntaxSYNTAXSYNTAXPrintWriter Output Stream Name new PrintWriter(newFileOutputStream(File Name,true));PrintWriter Output Stream Name new PrintWriter(newFileOutputStream(File Name, true));EXAMPLE§ ExampleEXAMPLEPrintWriter outputStream new rintWriter outputStream newPrintWriter(newFileOutputStream("out.txt", true));"GUFS UIJT TUBUFNFOU ZPV DBO VTF UIF NFUIPET println and print to"GUFS UIJT TUBUFNFOUprintlnandoldprintwriteto the file, and ZPV DBO VTF UIF NFUIPET the new text will be writtenafter thetext toinwrite to thefile, and ZPV NJHIU XBOU UP TFQBSBUF UIF EFDMBSBUJPO PG UIF the new text will be written after the old text inUIF GJMF *O QSBDUJDFUIF GJMF *O QSBDUJDFstreamvariableand ZPV NJHIU XBOU UP TFQBSBUF UIF EFDMBSBUJPO PG UIF the invocation of the constructor, as we did in Listing

Unfortunately, we cannot pass a file name to Scanner's constructoTUBUFNFOU PG UIF GPMMPXJOH GPSN XJMM PQFO UIF GJMF GPS JOQVU Although Scanner EPFT IBWF B DPOTUSVDUPS UIBU UBLFT B TUSJOH BSHVNFOU UIStream Name newScanner(newFile(File Name))stringScanneris interpretedas data, andnot thename of a file.Scanner IPXFWFEPFT IBWF B DPOTUSVDUPS UIBU BDDFQUT BT BO BSHVNFOU BO JOTUBODF PG BOPUIIfyour programa file fortherea fiisstandardclass, Fileattempts, and Filetohasopena constructorto reading,which we butcan passfile,Scanner's constructorthrowFileNotFoundExceptionAname.(The nextsection will willdescribethea classFile in more detail.) .So§ UseScanneropen a text file for isinputearlierin thischapter,toa FileNotFoundExceptionalso thrownTUBUFNFOU PG UIF GPMMPXJOH GPSN XJMM PQFO UIF GJMF GPS JOQVU Reading From a Text Fileother situations.Scanner Stream Name new Scanner(new File(File Name));/PUJDF UIBU UIF QSPHSBN JO -JTUJOH IBT TPNF HFOFSBM TJNJ E.g.:ScannerinputStream newScanner(newIf yourprogramattemptsto opena filefor reading,File(“out.txt”));but there is no sucUIF QSPHSBN JO -JTUJOH UIBU DSFBUFE B UFYU GJMF &BDI PQFOT UIF file, Scannerblocks,'s constructorwill throw a withFileNotFoundExceptionAs youthesatry-catchdoes somethingthe file, and then .closes§ Usethechapter,methodhasNextLine tois alsoreadearlierin thisa FileNotFoundExceptionthrown in certaiMPPL BU UIF TUBUFNFOUT JO -JTUJOH UIBU SFBE BOE EJTQMBZ UIF FOUJSother situations./PUJDF UIBU UIF QSPHSBN JO -JTUJOH IBT TPNF HFOFSBM TJNJMBSJUJFT Uwhile (inputStream.hasNextLine())UIF QSPHSBN JO -JTUJOH UIBU DSFBUFE B UFYU GJMF &BDI PQFOT UIF GJMF VTJO{try-catchStringblocks, doeswith the file, and then closes the file. Letlinesomething inputStream.nextLine();MPPL BU UIF TUBUFNFOUT JO -JTUJOH UIBU SFBE BOE EJTQMBZ UIF FOUJSF GJMF tLine()){This loopreads lineand thendisplays each line in the file, one at a timeString inputStream.nextLine();FOE PG UIF GJMF JT SFBDIFE 5IF TDSFFO PVUQVU TIPXO JO -JTUJOH System.out.println(line);

EFTDSJCFE JO 'JHVSF PG IBQUFS )PXFWFS XF IBWF OPU VTFE UIF NFUIPE hasNextLine CFGPSF *U SFUVSOT USVF JG BOPUIFS MJOF JO UIF GJMF JT BWBJMBCMF GPS input. Figure 10.3 summarizes this method and a few other analogous methods.Reading From a Text FileRECAP Reading a Text File§ SyntaxSYNTAX// Open the fileScanner Input Stream Name null;try{ new Scanner(new File(File Name));ER 10 / StreamsInput Stream Nameand File I/O}catch(FileNotFoundException e)(continued){Statements Dealing With The Exception}// Read the file using statements of the form:Input Stream Name.Scanner Method();// Close the fileInput Stream Name.close();

Example

Other Techniques§ The class File provides a way to represent filenames in a general way E.g.: new File(“out.txt”) – Create a File objectrepresents the name of a file§ Let the user enter the file name at the keyboard E.g.: String fileName keyboard.next();§ Use Path Names A path name specifies the folder containing a file E.g.: Scanner inputStream new Scanner(new File(“/User/yihong/out.txt”));

Help on Homework 4

Next Class§ Lab 8

String fileName "out.txt";//Could read file name from user PrintWriter outputStream null; try { outputStream new PrintWriter(fileName); } catch(FileNotFoundException e) { System.out.println("Error opening the file " fileName); System.exit(0); } Opening a