FILE IO Input and Output FILE I/O OVERVIEW A File is a 'persistent' collection of data Persistent means that the data is stored even after the program ends Files can store text, audio, images, video or anything else Files are stored in folders Folders are containers for files and folders I/O stands for Input/Output In this context it is input to and output from programs Input can be from the keyboard or a file or a mouse Output can be to the screen or to a file 2 BINARY VERSUS TEXT FILES All data and programs are ultimately just zeros and ones each digit can have one of two values, hence binary a bit is one binary digit a byte is a group of eight bits a byte can represent only 256 different values All files contain sequences of bytes (which are numbers)! Text files: the numbers represent characters Each datum is one byte Each datum represents a character using ASCII code Binar y files: the bits represent other types of encoded information, such as executable instructions or numeric data The datum may have varying byte lengths these files are easily read by the computer but not humans 3 BINARY FILE AS TEXT FILE EXAMPLE ÐÏࡱá > þÿ “ þÿÿÿ þÿÿÿ ‘ ’ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ Fð0 ÕÌ%ßØÐ^‹qüayÜÿØÿà JFIF K K ÿãMSO Palette ¸ÝûÀàûÅáûÇãûËãûËäûÍåûÏæûÑåûÒçûÔçûÖèû ×çûØèûØéûÚêûÜéûÝêûÞëûÞìûáëûáìûäìûäîûçìûçïûêïûìñûíïûñòûóôûù ÷ûªØû°Úû³Ûû´Üû¶Ûû·Ýû·Þû ¸ßûºÞû»Ýû»ßû¼àû½Þû¾Þû¾àû¿áûÀÞûÀâûÁàûÁáûÂáûÂâûÃßûÃáûÃâûÄáûÄâûÄãûÅâûÅãûÅäûÆàûÆáûÆâûÆãûÇâûÇäûÇåûÈâûÈãûÈäûÉáûÉãû ÉäûÉåûÊâûÊäûÊåûÊæûËåûÌãûÌäûÌåûÌæûÌçûÍãûÍäûÍæûÍçûÎäûÎåûÎæûÎçûÎèûÏãûÏåûÏçûÏèûÐäûÐåûÐæûÐçûÑæûÑçûÑèûÒäûÒæûÒèûÓäûÓæûÓçûÓ èûÓéûÔæûÔèûÕæûÕçûÕèûÕéûÖåûÖçûÖéû ×èû×éû×êûØæûØçûØêûØëûÙèûÙéûÙêûÚèûÚéûÚëûÚìûÛçûÛéûÛêûÛëûÜèûÜêûÜëûÜìûÜíûÝèûÝéûÝëû ÝìûÞèûÞêûÞíûßêûßëûßìûßíûßîûàéûàêûàëûàìûàíûàîûáíûáîûâêûâëûâìûâíûãëûãìûãíûãîûãïûäëûäíûäðûåëûåìûåíûåîûåïûæíûæîûæïûæðûçíûçîûçð ûçñûèîûèïûèðûèñûéîûéïûéðûéñûêìûêîûêðûêñûêòûëîûëïûëðûëñûìîûìðûìòûíîûíðûíñûíòûíóûîðûîñûîòûîôûïñûïòûïóûðïûðñûðòûðóûðõûññûñóûñôû òòûòóûòôûòõûóñûóóûóöûôóûôôûôõûõòûõóûõöûöôûö ÷û÷õûøöûùôûùøûûöûûøûþøûþúûþüûÿÛ C ")$+*($''-2@7-0=0''8L9=CEHIH+6OUNFT@GHEÿÛ C !!E.'.EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEÿÀ € €" ÿ Ä ÿÄ !1AQ"aq2B ‘¡R±ÁÑð#áÿÄ ÿÄ !1AaÿÚ ? ô‘‹>2VŽñåmQMüsF+Iïûa¯âGM •¾zÅ"1¦ÎÜ ·ww÷Nh• JN½>ñ• Æ2ÿ JÑ^r(˜ ¿:Ê ŒB7)Z±)üf‚q¨”Õï³ #e¡k‹š…‘ûï&P”¤Ò·¿u¬êNLº2¦#öÍ8ü\g) aã1òHýê±m]h]ý`F¥w©Wf ¡fˬx†¬¼Xòùw÷’sœ®³,e:÷`WøÌD• ÛÖ©ÂBþ¥»‹WšeB ‘m¾³Qo³£)~;ívÖLž—JZàiP•»Îeÿ 9¤õ”Á~Füuç*$„å-ú;þ¹ñå&Ð/·Æ2lÇûyÆ{ªÑâ8@ã•ïˬ æØ‘þÞråÄ·Åú½ç3®¾]÷þ•9v²NµÝw¯9U/ÔåSYÒ/ÆêŸï‘@÷~}^RÅv×^2¸f¨ nN ÷„x«Vµ¯¼’À‰¿úÊ”¾Ucô• iF ~ê¼f…H½¾<fepGå¼9V®šé{ÉK?R‘ušæˆD¯7‹ \NPûÞ$†žz¬• eE!ºÛþÙ4LêëÓŠ‘™mÿ 8³¸êOÏx®*?ë'ãZ$_¢²`ŸŸR[*ã÷uxàÓ:I¨(Ö3%VšÛ .*þ£qÿ ÝãÄŠPwedS¸+z|˜5)Jº|ÖiKø†Íþnðåh• X²Ch~z¼§Êi<ߌѺ®ïe#J®½`HÔÿ =×}dÓÉ¿ŠõèÌÜoÄ_®²[ñ{òb\£Å*'F‚Ï7þ1• í/UïÎSBD‰Uz<äpñZkWë»;|á"P;ìμ´ÔNõ…3—2_ý,N³GˆmmZ¦²åiòÝxÖó—)ZH%ë¼¢¼$6¢:¼¡¡>]ÿ _ΔG]»ÆO†›ïIpÛ³W^1*1jû¤Ì:øôWÞS8ÕH¥Ý˜4†5iZ< zÉŒNVtöûÊeÊQ)ªÖUßîÓ}¸Œ’K—ÖïÆ^VÅüfR1¤’˜ 4 ASCII Table 0 1 2 3 4 5 6 7 8 9 10 11 12 0 NUL LF DC4 RS ( 2 < F P Z d n x 1 SOH VT NAK US ) 3 = G Q [ e o y 2 STX FF SYN SP * 4 > H R \ f p z 3 ETX CR ETB ! + 5 ? I S ] g q { 4 EOT SO CAN " , 6 @ J T ^ h r | 5 ENQ SI EM # 7 A K U _ i s } 6 7 ACK BEL DLE DC1 SUB ESC $ % . / 8 9 B C L M V W ` a j k t u ~ DEL 8 BS DC2 FS & 0 : D N X b l v 9 HT DC3 GS ' 1 ; E O Y c m w Consider a file containing the following sequence of byte values. What appears if this file is opened in NotePad? 74 97 118 97 32 105 115 10 70 117 110 33 5 DECIMAL REPRESENTATION decimal digit 8 4 5 position name hundreds tens ones 102 101 100 positional value 6 GENERAL REPRESENTATION Numbers are represented in an arbitrary base (or radix) using the formula a n R n + a n-1 R n-1 + a n-2 R n-2 + ... + a1R1 + a0R0 • a is a digit in the base numbering scheme • R is the base (or radix) • n is an exponent that corresponds to the positional value of the digit 7 COMMON CS NUMBERING SYSTEMS Largest Single Digit Base Only Valid Digits 2 binary 1 01 8 octal 7 01234567 10 decimal 9 0123456789 F (f) 0 1 2 3 4 5 6 7 8 9AB CDEF (a b c d e f) 16 hexadecimal Problem: convert 111102 to decimal (base 10) convert 368 to decimal convert 1E16 to decimal 8 CONVERSION TABLE Conversion Table Binary Octal Decimal Hexadecimal 0 0 0 0 1 1 1 1 10 2 2 2 11 3 3 3 100 4 4 4 101 5 5 5 110 6 6 6 111 7 7 7 1000 10 8 8 1001 11 9 9 1010 12 10 A 1011 13 11 B 1100 14 12 C 1101 15 13 D 1110 16 14 E 1111 17 15 F 10000 20 16 10 9 DECIMAL TO BINARY CONVERSION Algorithm Conver tToBinar y(X) Input: X is a decimal number Output: B is a sequence of binary digits representing X Let B be an empty sequence of binary digits while X is greater than or equal to 1 do set A to the remainder of the non-integer division of (X/2) set X to the quotient (non-remainder) of (X/2) place A at the beginning of the sequence B return B Problem: convert 81910 to binary Answer: 11001100112 10 PRIMITIVE DATA T YPES MEMORY STORAGE AND RANGES Type Kind of Value Memory Used Size Range byte Integer Number 1 byte -128 to 127 short Integer Number 2 bytes -32768 to 32767 int Integer Number 4 bytes -2,147,483,648 to 2,147,483,647 long Integer Number 8 bytes -9,223,372,036,854,775,808 to 9,223,374,036,854,775,808 float Real Number 4 bytes +/- 3.4028… x 10+38 to +/- 1.4023… x 0-45 double Real Number 8 bytes +/- 1.767… x 10+308 to +/- 4.940… x 0-324 char Single character 2 bytes 0 to 65535 11 TEXT VERSUS BINARY FILES Text files are more readable by humans Binar y files are more ef ficient computers read and write binary files more easily than text Java binar y files are por table they can be used by Java on different machines. Reading and writing binary files is normally done by a program text files are generally used only to communicate with humans Java Text Files Source files Occasionally input files Occasionally output files Java Binary Files Executable files (created by compiling source files) Usually input files Usually output files 12 TEXT FILES Two primary classes for manipulating text files: PrintWriter is used for creating and writing to files BufferedReader is used for reading files These classes are found in the “java.io” package. You must include an “import java.io.*;” line if you use these classes. Text files contain only “words” or “Strings”. Everything written into a text file is first converted to a String (even numbers!). 13 FILE SYSTEM Users smith jones hw1.java hw2.java Root Directory hw1.class Java provides a File class for working with directories and files. The File class is not used to read/write from/to files, but to provide information about files. hw1.class smith Stuff.txt 14 FILE CLASS To create a File object File aFile = new File(“hw1.java”); The file is NOT created on disk. The file may not exist. Can check properties of the file… boolean doesFileExist = aFile.exists(); boolean isTheFileADirectory = aFile.isDirectory(); int fileLength = aFile.length(); Can create and delete files boolean operationOK = file.delete(); // deletes the file from disk boolean operationOK = file.createNewFile(); //creates empty file 15 STREAMS Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) Input stream: a stream that provides input to a program (can be from a keyboard, mouse, or file) System.in is an input stream Output stream: a stream that takes output from a program System.out is an output stream 16 STREAMS Input Stream Program Source The program reads from the input stream Output Stream Program Destination The program write to the output stream 17 READING AND WRITING No matter where the information is coming from or going to and no matter what type of data is being read or written, the algorithms for reading and writing data are usually the same : Reading Writing open a stream while more data exists read some data process the data close the stream open a stream while more data exists process the data write the data close the stream 18 PRINTWRITER OVERVIEW To open/create a text file for output, create a PrintWriter object. PrintWriter fout = new PrintWriter(new FileWriter("out.txt")); Then you can use print and println to write to the file just like you would use System.out.print() and System.out.println() to write to the terminal. fout.println(“hello”) \n o l l e h 19 PRINTWRITER Constructor Summary PrintWriter output = new PrintWriter(new FileWriter(“name.txt”)); Method Summary void print(boolean) Prints a boolean. May throw an IOException void print(char) Prints a character. void print(double) Prints a double. void print(float) Prints a float. void print(int) Prints an integer. void print(long) Prints a long. void print(Object) Prints an object. void print(String) Prints a String. Also has println methods corresponding to each of the above 20 PRINTWRITER A PrintWriter always outputs TEXT (STRINGS). 34 false 1993.128 “Hello” a JFrame int boolean double String Object fout.print( ); String 21 PRINTWRITER A print writer must be closed! Use the “close()” method! If data is printed to a print writer but the print writer is never closed, the output file may not contain all of the printed data. PrintWriter fout = new PrintWriter(new FileWriter(“out.jpg”)); for(int i=0; i<10; i++){ fout.println(“Hello”); } Writing fout.close(); open a stream while more data exists process the data write the data close the stream 22 WARNING: OVERWRITING A FILE Opening a print-writer file creates an empty file Opening a print-writer file creates a new file if it does not already exist Opening a print-writer file that already exists eliminates the old file and creates a new, empty one. Data in the original file is lost! Warning Will Robinson 23 COMMAND-LINE OPTIONS (A BRIEF DESCRIPTION) When a program is executed the computer is “commanded” to run the program. When a program is executed, the meaning is “invoke the main method”. The main method specifies an “array of Strings” as input The value of this array is determined by the “command-line” that was used to executed the program Each “word” following the name of the class to execute on the command-line is one element of the array 24 COMMAND-LINE OPTIONS (A BRIEF DESCRIPTION) Use the class below to experiment with command -line options. Tr y to predict the output given the following scenarios: java CommandLineDemo java CommandLineDemo opt1 opt2 opt3 opt4 java CommandLineDemo file1.txt file2.txt java CommandLineDemo 1 2 356 java CommandLineDemo 1-x 18 numbers java CommandLineDemo “once upon a time” class CommandLineDemo { public static void main(String[] args) { for(int i=0; i<args.length; i++){ System.out.println(args[i]); } } } 25 SAVING DATA TO A TEXT FILE i mpor t j ava.i o.*; Write 10 randomly generated (0-100) numbers to a text file where each number is c lass Ar rayWr iter { pu bli c sta tic voi d mai n(St rin g[] a rgs) {on the same line and separated by a space character. Pr intWr iter fo ut = null ; The // crea te a nd initi aliz e a n arr ay o bje ctcommand-line arguments are: arg[0] is the name of the file to create in t[] d ata = n ew in t[10 ]; fo r(int i=0 ; i <data .len gth ; i++ ) { data [i] = ( int)( Math .ra ndom( )*10 1); } tr y { fou t = n ew P rin tWrit er(n ew F ileW rit er(ar gs[0 ])) ; for(i nt i =0; i<da ta.l eng th; i ++) { fo ut.p rin t(dat a[i] + " "); } fou t.clo se() ; } catch (IOE xce ption ioe ) { Syste m.ou t.p rintl n("E rro r wri ting to " + a rgs[ 0]) ; } } May throw an IOException! } 26 BUFFEREDREADER Used for reading text files Constructor Summary BufferedReader fin = new BufferedReader(new FileReader(“data.txt”)); Method Summary int read() – reads a single character but converts it to an int String readLine() – reads an entire line of text, returns “null” if the end of the file is encountered Both of the “read” methods throw an IOException BufferedReader has no methods to read in numbers so you must read in a String and convert 27 READING DATA FROM A TEXT FILE import java.io.*; class ArrayReader { public static void main(String[] args) { BufferedReader fin = null; String line; int[] data = new int[10]; Read 10 numbers from a file where each number is on its own line. Prints the largest, smallest, and average of the numbers. The command-line arguments are: arg[0] is the name of the file to read from try { fin = new BufferedReader(new FileReader(args[0])); for(int i=0; i<10; i++) { data[i] = fin.readLine(); // THERE IS A PROBLEM HERE! } fin.close(); } catch(IOException ioe) { System.out.println("Error reading from " + args[0]); System.exit(0); } int max = 0; // index of the maximum value int min = 0; // index of the minimum value int total = 0; // cumulative total for(int i=0; i<data.length; i++) { if(data[i] > data[max]) max = i; if(data[i] < data[min]) min = i; total = total + data[i]; } System.out.println("Minimum value is " + data[min]); System.out.println("Maximum value is " + data[max]); System.out.println("Average value is " + total/(double)10); } } 28 READING DATA FROM A TEXT FILE import java.io.*; import java.util.*; class ArrayReader { public static void main(String[] args) { BufferedReader fin = null; String line; int[] data = new int[10]; Read 10 numbers from a file where each number is on its own line. Prints the largest, smallest, and average of the numbers. The command-line arguments are: arg[0] is the name of the file to create try { fin = new BufferedReader(new FileReader(args[0])); for(int i=0; i<10; i++) { data[i] = Integer.valueOf(fin.readLine()).intValue(); // Convert String to int } fin.close(); } catch(IOException ioe) { System.out.println("Error reading from " + args[0]); System.exit(0); } int max = 0; // index of the maximum value int min = 0; // index of the minimum value int total = 0; // cumulative total for(int i=0; i<data.length; i++) { if(data[i] > data[max]) max = i; if(data[i] < data[min]) min = i; total = total + data[i]; } System.out.println("Minimum value is " + data[min]); System.out.println("Maximum value is " + data[max]); System.out.println("Average value is " + total/(double)10); } } 29 DETECTING THE END OF A FILE A common programming situation is to read data from an input file but not know how much data the file contains . In these situations you need to check for the end of the file. There are three common ways to test for the end of a file: 1. Test for a special value that signals the end of the file 2. Throw and catch an end-of-file exception 3. Place a sentinal value at the end of a file and test for it 30 TESTING FOR END OF FILE IN A TEXT FILE When readLine tries to read beyond the end of a text file it returns the special value null so you can test for null to stop processing a text file read returns -1 when it tries to read beyond the end of a text file the int value of all ordinary characters is nonnegative 31 USING READLINE() FOR LINE-BY-LINE FILE PROCESSING readLine throws an IOException When using readLine test for null import java.io.*; class FilePrintDemo { public static void main(String[] args) { int count = 0; try { BufferedReader in = new BufferedReader(new FileReader(args[0])); String line = in.readLine(); while (line != null) { count++; System.out.println(count + “\t" + line); line = in.readLine(); } in.close(); } catch(IOException e) { System.out.println(e.getMessage()); System.out.println(“Error with file “ + args[0]); System.exit(0); } } } 32 USING READ() FOR CHARACTER-BYCHARACTER FILE PROCESSING read throws an IOException When using read test for -1 import java.io.*; class FilePrintDemo2 { public static void main(String[] args) { int count = 1; try { BufferedReader in = new BufferedReader(new FileReader(args[0])); int c = in.read(); if(c != -1) System.out.print(count + “\t”); while (c != -1) { System.out.print(String.valueOf((char)c)); if(c == ‘\n’) System.out.print(++count + “\t”); c = in.read(); } in.close(); } catch(IOException e) { System.out.println(e.getMessage()); System.out.println(“Error with file “ + args[0]); System.exit(0); } } } 33 READING DATA FROM A TEXT FILE import java.io.*; class ArrayReader { private static int MAX=1000; public static void main(String[] args) { BufferedReader fin = null; String line; int[] data = new int[MAX]; Read zero or more (up to some upper limit) numbers from a file where each number is on its own line. Prints the largest, smallest, and average of the numbers. The command-line arguments are: arg[0] is the name of the file to create try { fin = new BufferedReader(new FileReader(filename)); while((line = fin.readLine()) != null) { data[i] = Integer.parseInt(line); } fin.close(); } catch(IOException ioe) { System.out.println("Error reading from " + args[0]); System.exit(0); } int max = 0; // index of the maximum value int min = 0; // index of the minimum value int total = 0; // cumulative total for(int i=0; i<data.length; i++) { if(data[i] > data[max]) max = i; if(data[i] < data[min]) min = i; total = total + data[i]; } System.out.println("Minimum value is " + data[min]); System.out.println("Maximum value is " + data[max]); System.out.println("Average value is " + total/(double) 10); } } 34 READING DATA FROM A TEXT FILE import java.io.*; class ArrayReader { private static int MAX=1000; public static void main(String[] args) { BufferedReader fin = null; String line; int[] data = new int[MAX]; int count=0; Read zero or more (up to some upper limit) numbers from a file where each number is on its own line. Prints the largest, smallest, and average of the numbers. The command-line arguments are: arg[0] is the name of the file to create try { fin = new BufferedReader(new FileReader(filename)); while((line = fin.readLine()) != null) { data[count++] = Integer.valueOf(line).intValue(); } fin.close(); } catch(IOException ioe) { System.out.println("Error reading from " + args[0]); System.exit(0); } int max = 0; // index of the int min = 0; // index of the int total = 0; // cumulative for(int i=0; i<count; i++) { if(data[i] > data[max]) max = if(data[i] < data[min]) min = total = total + data[i]; } maximum value minimum value total i; i; System.out.println("Minimum value is " + data[min]); System.out.println("Maximum value is " + data[max]); System.out.println("Average value is " + total/(double)count); } } 35 READING DATA FROM A TEXT FILE import java.io.*; import java.util.*; class ArrayReader { private static int MAX=1000; public static void main(String[] args) { BufferedReader fin = null; String line; int[] data = new int[MAX]; int count=0; Read zero or more (up to some upper limit) numbers from a file where each number is on the same line and separated by a space. Prints the largest, smallest, and average of the numbers. The command-line arguments are: arg[0] is the name of the file to create try { fin = new BufferedReader(new FileReader(filename)); while((line = fin.readLine()) != null) { data[count++] = Integer.parseInt(line); } fin.close(); } catch(IOException ioe) { System.out.println("Error reading from " + args[0]); System.exit(0); } int max = 0; // index of the int min = 0; // index of the int total = 0; // cumulative for(int i=0; i<count; i++) { if(data[i] > data[max]) max = if(data[i] < data[min]) min = total = total + data[i]; } } maximum value minimum value total i; i; System.out.println("Minimum value is " + data[min]); System.out.println("Maximum value is " + data[max]); System.out.println("Average value is " + total/(double)count); } 36 WORD-BY-WORD PROCESSING There are BufferedReader methods to read a line and a character, but not just a single word Scanner is a class that provides more flexible 'parsing' Parsing is the act of taking individual letters and grouping them The scanner groups letters into primitive types and Strings Scanners work by Separating groups of letters by 'delimiter' characters Converting each group of letters into some primitive type or String type A delimiter any character that is never part of a 'thing' defaults to the "white space" characters: space (‘ ‘) tab (‘\t’) newline (‘\n’) 37 WORD-BY-WORD PROCESSING Construction Scanner s1 = new Scanner( new File("data.txt") ); Scanner s2 = new Scanner( "3 12 55\n1 9 31" ); Control the delimiters s1.useDelimiters("[ \n\t]"); // uses space, newline, tab s1.useDelimiters("[.1]"); // uses period, 1 s1.reset(); // uses defaults Obtain the next 'thing' s1.nextInt() s1.nextByte() s1.nextBoolean() s1.nextLong() s1.nextDouble() s1.next() … 38 SCANNER API You can construct a scanner by passing in a String: new Scanner("The quick fox jumped …"); File: new Scanner( new File( "input.txt" ) ); InputStream: new Scanner( System.in ); You can ask the scanner what 'type' of thing comes next. Each of the "has<T YPE>" methods returns a boolean. Each also throws NoSuchElementException, IllegalStateException, and InputMismatchException. These are RuntimeExceptions. scanner.hasNextInt() scanner.hasNextDouble() scanner.hasNextBoolean() scanner.hasNext() … others not shown 39 WORD-BY-WORD PROCESSING You can read the next item and return it (advancing the scanner). The return type is implied by the method name. int x = scanner.nextInt() double y = scanner.nextDouble() boolean z = scanner.nextBoolean() String token = scanner.next(). Example: Scanner s1 = new Scanner("9 false 3.2"); boolean b1 = s1.hasNextInt(); boolean b2 = s1.hasNextBoolean(); boolean b3 = s1.hasNextDouble(); int x = s1.nextInt(); b1 = s1.hasNextInt(); b2 = s1.hasNextBoolean(); b3 = s1.hasNextDouble(); b1 = s1.hasNext(); 40 SCANNER If a scanner is used to read data from a file; be sure to close the scanner when you are done with it. Scanner scanner = new Scanner( new File( "input.txt") ); // read lots of data from the scanner scanner.close(); // THIS IS IMPORTANT Note that once a scanner is closed, any "get -the-next-thing" method will throw an IllegalStateException. 41 READING DATA FROM A TEXT FILE import java.io.*; import java.util.*; class ArrayReader { private static int MAX=1000; public static void main(String[] args) { int[] data = new int[MAX]; int count = 0; Read zero or more (up to some upper limit) numbers from a file where each number is on the same line and separated by a space. Prints the largest, smallest, and average of the numbers. The command-line arguments are: try { S c a n n e r s c a n n e r = n e w S c a n n e r ( n e w F i l e ( a r g s [ 0 ] ) ) ;arg[0] is the name of the file to create while(scanner.hasNextInt()) { data[count++] = scanner.nextInt() ; } scanner.close(); } catch(Exception e) { System.out.println("Error reading from " + args[0]); System.exit(0); } int max = 0; // index of the int min = 0; // index of the int total = 0; // cumulative for(int i=0; i<count; i++) { if(data[i] > data[max]) max = if(data[i] < data[min]) min = total = total + data[i]; } maximum value minimum value total i; i; System.out.println("Minimum value is " + data[min]); System.out.println("Maximum value is " + data[max]); System.out.println("Average value is " + total/(double)count); } } 42 READING DATA FROM A TEXT FILE import java.io.*; import java.util.*; class ArrayReader { private static int MAX=1000; public static void main(String[] args) { int[] data = new int[MAX]; int count = 0; Read zero or more (up to some upper limit) numbers from a file where there are zero or more numbers on each line! Prints the largest, smallest, and average of the numbers. The command-line arguments are: arg[0] is the name of the file to create try { Scanner scanner = new Scanner( new File ( args[0] ) ); while(scanner.hasNextInt()) { data[count++] = scanner.nextInt() ; } scanner.close(); } catch(Exception e) { System.out.println("Error reading from " + args[0]); System.exit(0); } //////////////////////// // other code goes here //////////////////////// System.out.println("Minimum value is " + data[min]); System.out.println("Maximum value is " + data[max]); System.out.println("Average value is " + total/(double)count); } } 43 BINARY FILES The most common stream classes for binar y files: DataInputStream: used to read a file DataOutputStream: used to write to a file The output files are binary and can store any of the primitive data types (int, char, double, etc.) and the Object String type The files can be read by other Java programs but are not printable Must include “import java.io.*;” to use these classes. An IOException might be thrown when writing data 44 DATAOUTPUTSTREAM METHOD SUMMARY After the binary file is opened you can send data to it by using one of the following methods: void writeChar(int c) void writeInt(int n) void writeDouble(double x) void writeBoolean(boolean b) void writeUTF(String s) Note that each write method throws IOException 45 WHAT IS UTF?? Use the writeUTF method to output a value of type String. There is no writeString method! UTF stands for Universal Text Format which is a special version of Unicode Unicode: a text code that uses 2 bytes per character. Designed to accommodate languages with a dif ferent alphabet or no alphabet (such as Chinese and Japanese) ASCII: also a text code, but it uses just 1 byte per character. The most common code for English and languages with a similar alphabet UTF is a modification of Unicode that uses just one byte for ASCII characters while allowing 2 bytes for other languages 46 OPENING AN OUTPUT FILE To open a file named “numbers.dat” for binary output: DataOutputStream fout = new DataOutputStream(new FileOutputStream(“numbers.dat”)); Consider the following sequence of statements: fout.writeInt(10); fout.writeInt(20); fout.writeBoolean(true); fout.writeDouble(12.0); fout.close(); How many bytes of data does this file contain? 47 SAVING DATA TO A BINARY FILE i mpor t j ava.i o.*; Write 10 int values to a binary file. Each number is randomly generated in the c lass Ar rayWr iter { pu bli c sta tic voi d mai n(St rin g[] a rgs) {interval [0..100]. Da taOut putS tre am fo ut = nu ll; The command-line arguments are: arg[0] // crea te a nd initi aliz e a n arr ay o bje ct is the name of the file to create in t[] d ata = n ew in t[10 ]; fo r(int i=0 ; i <data .len gth ; i++ ) { data [i] = ( int)( Math .ra ndom( )*10 1); } tr y { fou t = n ew D ata Outpu tStr eam (new F ileO utp utStr eam( arg s[0]) ); for(i nt i =0; i<da ta.l eng th; i ++) { fo ut.w rit eInt( data [i] ); } fou t.clo se() ; } catch (IOE xce ption ioe ) { Syste m.ou t.p rintl n("E rro r wri ting to " + args [0] ); } } } 48 DATAINPUTSTREAM METHODS For every DataOutputStream method there is a corresponding DataInputStream method You can read data from a binary input file by using methods defined in DataInputStream int readInt() double readDouble() boolean readBoolean() String readUTF() Note that each write method throws IOException 49 OPENING AN OUTPUT FILE To open a file named “numbers.dat” for binary input: DataInputStream fin = new DataInputStream(new FileInputStream(“numbers.dat”)); Consider the following sequence of statements: int x= fin.readInt(); int y = fin.readInt(); boolean b = fin.readBoolean(); double z = fin.readDouble(); fin.close(); What occurs if the first two lines are replaced with long z = fin.readLong(); 50 INPUT FILE EXCEPTIONS A FileNotFoundException is thrown if the file is not found when an attempt is made to open a file Each read method throws IOException If a read goes beyond the end of the file an EOFException is thrown 51 AVOIDING COMMON DATAINPUTSTREAM FILE ERRORS Input files can contain a mix of data types. It is up to the programmer to know their order and use the correct read method There is no error message (or exception) if you read the wrong data type! DataInputStream works with binary, not text files As with an output file, close the input file when you are done with it 52 THE EOFEXCEPTION CLASS Many (but not all) methods that read from a file throw an end-of-file exception (EOFException) when they try to read beyond the file Most of the DataInputStream methods throw it The end-of-file exception can be used in an "infinite" (while(true)) loop that reads and processes data from the file the loop terminates when an EOFException is thrown The program is written to continue normally after the EOFException has been caught 53 USING EOFEXCEPTION Problem: Write code to print the values in a binary file named “numbers.dat” which contains zero or more int values. try { DataInputStream inputStream = new DataInputStream(new FileInputStream("numbers.dat")); int n; Intentional "infinite" loop to process data from input file Loop exits when end-of-file exception is thrown Processing continues after EOFException: the input file is closed System.out.println("Reading ALL the integers"); System.out.println("in the file numbers.dat."); try { while (true) { n = inputStream.readInt(); System.out.println(n); } } catch(EOFException e) { System.out.println("End of reading from file."); } inputStream.close(); } catch(FileNotFoundException e) { System.out.println("Cannot find file numbers.dat."); } catch(IOException e2) { System.out.println("Problem with input from file numbers.dat."); } Note order of catch blocks: the most specific is first and the most general last 54