input and output file io. 2 i/o stands for input/output in this context it is input to and output...

53
Input and Output FILE IO

Upload: dora-brown

Post on 08-Jan-2018

236 views

Category:

Documents


0 download

DESCRIPTION

3 FILE SYSTEM Users jones smith hw1.javahw2.javahw1.class Stuff.txt Root Directory 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.

TRANSCRIPT

Page 1: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

Input and OutputFILE IO

Page 2: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

2

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 mouseOutput can be to the screen or to a fileAdvantages of file I/O

permanent (persistent) copy of data output from one program can be input to another input can be automated (rather than entered manually)

I/O OVERVIEW

Page 3: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

3

FILE SYSTEM

Users

jones smith

smithhw1.java hw2.java hw1.class hw1.class

Stuff.txt

Root Directory

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.

Page 4: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

4

To create a File object File aFile = new File(“hw1.java”);

The file is NOT created on disk.

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

FILE CLASS

Page 5: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

5

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

STREAMS

Page 6: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

6

STREAMS

Input Stream

Output Stream

Page 7: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

7

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 AND WRITING

Readingopen a streamwhile more data exists

read some dataprocess the data

close the stream

Writingopen a streamwhile more data exists

process the datawrite the data

close the stream

Page 8: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

8

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

Binary 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

BINARY VERSUS TEXT FILES

Page 9: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

9

Ð Ï à ¡ ± á > þ ÿ “ þ ÿ ÿ ÿ þ ÿ ÿ ÿ ‘ ’ � �ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ   F ð 0 Õ Ì % ß Ø Ð ^ ‹ q ü ay Ü ÿ Ø ÿ à J F I F K K ÿ ã M S O Pa l e t t e ¸ Ýû À à û Å á û Ç ã û Ë ã û Ë ä û Í å û Ï æ û Ñ å û Ò ç û Ô ç û Ö è û × ç û Ø è û Ø é û Ú ê û Ü é û Ýê û Þ ë û Þ ì û á ë û á ì û ä ì û ä î û ç ì û ç ï û ê ï û ì ñ û í ï û ñ ò û ó ô û ù ÷ ûª Ø û ° Ú û ³ Û û´ Ü û ¶ Û û · Ýû · Þ û ¸ ß û º Þ û » Ýû » ß û ¼ à û ½ Þ û ¾ Þ û ¾ à û ¿ á û À Þ û À â û Á à û Á á û  á û  â û Ã ß û à á û à â û Ä á û Ä â û Ä ã û Å â û Å ã û Å ä û Æ à û Æ á ûÆ â û Æ ã û Ç â û Ç ä û Ç å û È â û È ã û È ä û É á û É ã û É ä û É å û Ê â û Ê ä û Ê å û Ê æ û Ë å û Ì ã û Ì ä û Ì å û Ì æ û Ì ç û Í ã û Í ä û Í æ û Í ç û Î ä û Î å û Î æ û Î ç û Î è û Ï ã û Ïå û Ï ç û Ï è û Ð ä û Ð å û Ð æ û Ð ç û Ñ æ û Ñ ç û Ñ è û Ò ä û Ò æ û Ò è û Ó ä û Ó æ û Ó ç û Ó è û Ó é û Ô æ û Ô è û Õ æ û Õ ç û Õ è û Õ é û Ö å û Ö ç û Ö é û × è û × é û ×ê û Ø æ û Ø ç û Ø ê û Ø ë û Ù èû Ù é û Ù êû Ú è û Ú é û Ú ë û Ú ì û Û ç û Û é û Û ê û Û ë û Ü è û Ü ê û Ü ë û Ü ì û Ü í û Ýè û Ýéû Ýë û Ý ì û Þ è û Þ ê û Þ í û ß ê û ß ë û ß ì ûß í û ß î û à é û à ê û à ë û à ì û à í û à î û á í û á î û â ê û â ë û â ì û â í û ã ë û ã ì û ã í û ã î û ã ï û ä ëû ä í û ä ð û å ë û å ì û å í û å î û å ï û æ í û æ î û æ ï û æ ð û ç í û ç î û ç ðû ç ñ û è î û è ï û è ð û è ñ û é î û é ï û é ð û é ñ û ê ì û ê î û ê ð û ê ñ û ê ò û ë î û ë ï û ë ð û ë ñ û ì î û ì ð û ì ò û í î û í ð û í ñ û í ò û í ó û î ð û î ñ û î ò û î ô û ï ñ û ï ò û ï ó û ð ï ûð ñ û ð ò û ð ó û ð õ û ñ ñ û ñ ó û ñ ô û ò ò û ò ó û ò ô û ò õ û ó ñ û ó ó û ó ö û ô ó û ô ô û ô õ û õ ò û õ ó û õ ö û ö ô û ö ÷ û ÷ õ û ø ö û ù ô û ù ø û û ö û û ø û þ ø û þ ú û þ üû ÿ Û C

" ) $ + * ( $ ' ' - 2 @ 7 - 0 = 0 ' ' 8 L 9 = C E H I H + 6 O U N F T @ G H E ÿ Û C

! ! E . ' . E E E E E E E E E E E E E E E E E E E E E E E E E E E E E E E E E E E E E E E E E E E E E E E E E E ÿ À € € " ÿ Ä ÿ Ä - !1 A Q " a q 2 B ‘ ¡ R ± Á Ñ ð # áÿ Ä ÿ Ä ! 1 A aÿ Ú ? ô ‘ ‹ > 2 V Ž ñ å m Q M ü s F + I ï û a ¯ â G M ¾ z Å " 1 ¦ Î Ü · w w ÷ N h J N ½ > ñ Æ 2 ÿ � � � �J Ñ ^ r ( ˜ ¿ : Ê Œ B 7 ) Z ± ) ü f ‚ q ¨ ” Õ ï ³ # e ¡ k ‹ š … ‘ û ï & P ” ¤ Ò · ¿ u ¬ ê N L º 2 ¦ # ö Í 8 ü \ g )� � a ã 1 ò H ý ê ± m ] h ] ý ` F ¥ w © W f¡ f Ë ¬ x † ¬ ¼ X ò ù w ÷ ’ s œ ® ³ , e : ÷ ` Wø Ì D Û Ö ©  B þ ¥ » ‹ W š e B ‘ m ¾ ³ Q o ³ £ ) ~ ; í v Ö L ž — J Z à i P • » Î e ÿ �9 ¤ õ ” Á ~ Fü u ç * $ „ å - ú ; þ ¹ ñ å & Ð / · Æ 2 l Ç û y Æ { ª Ñ â 8 @ ã - • ï Ë ¬ æ Ø ‘ þ Þ r å Ä · Å ú ½ ç 3 ® ¾ ] ÷ þ 9 v ² N µ Ý w ¯ 9 U / Ô å - S YÒ /� �Æ ê Ÿ ï ‘ @ ÷ ~ } ^ R Å v × ^ 2 ¸ f ¨   n N ÷ „ x « V µ ¯ ¼ ’ À ‰ ¿ ú Ê ” ¾ U c ô i F ~ ê ¼ f … H ½ ¾ < f e p G å ¼ 9 V ® š é { É K ? R ‘ u š æ ˆ D ¯ 7 ‹ \ N P û Þ $ † ž z ¬ e E !� � �º Û þ Ù 4 L ê ë Ó Š ‘ ™ m ÿ 8 ³ ¸ ê O Ï x ® * ? ë ' ã Z $ _ ¢ ² ` Ÿ Ÿ R [ * ã ÷ u x à Ó : I ¨ ( Ö 3 % V š Û . * þ £ q ÿ Ýã Ä Š P w e d S ¸ + z | ˜ 5 ) J º |� �Ö i K ø † Í þ n ð å h X ² C h ~ z ¼ § Ê i < ß Œ Ñ º ® ï e # J ® ½ ` H Ô ÿ = × } d Ó É ¿ Š õ è Ì Ü o Ä _ ® ² [ ñ { ò b \ £ Å * ' F‚ Ï 7 þ 1 í / U ï Î S B D ‰ U z < ä p ñ Z k Wë » ; |� �á " P ; ì Î ¼ ´ Ô N õ … 3 — 2 _ ý, N ³ G ˆ m m Z ¦ ² å i ò Ý x Ö ó — ) Z H % ë ¼ ¢ ¼ $ 6 ¢ : ¼ ¡ ¡ > ] ÿ _ Î ” G ] » Æ O † › ï I p Û ³ W ^ 1 * 1 j û ¤ Ì : ø ô W Þ S 8 Õ H ¥ Ý ˜ 4 † 5 i Z < z É Œ N V t ö û Ê e Ê Q ) ª Ö U ß î Ó } ¸ Œ ’ K — Ö ï Æ ^ V Å ü f R 1 ¤ ’ ˜

BINARY FILE AS TEXT FILEEXAMPLE

Page 10: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

10

ASCII Table 0 1 2 3 4 5 6 7 8 9 0 NUL SOH STX ETX EOT ENQ ACK BEL BS HT 1 LF VT FF CR SO SI DLE DC1 DC2 DC3 2 DC4 NAK SYN ETB CAN EM SUB ESC FS GS 3 RS US SP ! " # $ % & ' 4 ( ) * + , - . / 0 1 5 2 3 4 5 6 7 8 9 : ; 6 < = > ? @ A B C D E 7 F G H I J K L M N O8 P Q R S T U V W X Y 9 Z [ \ ] ^ _ ` a b c 10 d e f g h i j k l m 11 n o p q r s t u v w 12 x y z { | } ~ DEL

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

Page 11: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

11

DECIMAL REPRESENTATION

decimal digit 8 4 5

position name hundreds tens ones

positional value 102 101 100

Page 12: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

12

Numbers are represented in an arbitrary base (or radix) using the formula

anRn + an-1Rn-1 + an-2Rn-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

GENERAL REPRESENTATION

Page 13: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

13

COMMON CS NUMBERING SYSTEMS

Base Largest Single Digit Only Valid Digits

2 binary 1 0 1

8 octal 7 0 1 2 3 4 5 6 7

10 decimal 9 0 1 2 3 4 5 6 7 8 9

16 hexadecimal F (f)0 1 2 3 4 5 6 7 8 9 A B C D E F(a b c d e f)

Problem: convert 111102 to decimal (base 10)convert 368 to decimalconvert 1E16 to decimal

Page 14: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

14

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

Page 15: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

15

Algorithm ConvertToBinary(X)Input: X is a decimal numberOutput: B is a sequence of binary digits representing XLet B be an empty sequence of binary digitswhile 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

DECIMAL TO BINARY CONVERSION

Problem: convert 81910 to binaryAnswer: 11001100112

Page 16: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

16

PRIMITIVE DATA TYPES 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

Page 17: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

17

Text files are more readable by humans Binary files are more efficient

computers read and write binary files more easily than text Java binary files are portable

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

TEXT VERSUS BINARY FILES

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

Page 18: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

18

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!).

TEXT FILES

Page 19: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

19

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.

PRINTWRITER OVERVIEW

fout.println(“hello”)hello\n

Page 20: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

20

Constructor Summary PrintWriter output = new PrintWriter(new

FileWriter(“name.txt”));Method Summary

void print(boolean) Prints a boolean. 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

PRINTWRITER

May throw an IOException

Page 21: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

21

PRINTWRITER

A PrintWriter always outputs TEXT (STRINGS).

fout.print( );

int boolean double String Object

String

34 false 1993.128 “Hello” an ALabel

Page 22: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

22

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

PrintWriter fout = new PrintWriter(new FileWriter(“out.jpg”));for(int i=0; i<10; i++){ fout.println(“Hello”);}fout.close(); Writing

open a streamwhile more data exists

process the datawrite the data

close the stream

Page 23: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

23

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: OVERWRITING A FILE

Warning Will Robinson

Page 24: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

24

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

COMMAND-LINE OPTIONS(A BRIEF DESCRIPTION)

Page 25: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

25

Use the class below to experiment with command-l ine options. Try to predict the output given the fol lowing scenarios:

COMMAND-LINE OPTIONS(A BRIEF DESCRIPTION)

class CommandLineDemo {public static void main(String[] args) {

for(int i=0; i<args.length; i++){ System.out.println(args[i]);

}}

}

java CommandLineDemo “once upon a time”java CommandLineDemo 1-x 18 numbers

java CommandLineDemo file1.txt file2.txtjava CommandLineDemo 1 2 356

java CommandLineDemo opt1 opt2 opt3 opt4java CommandLineDemo

Page 26: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

26

import java.io.*;

class ArrayWriter { public static void main(String[] args) { PrintWriter fout = null;

// create and initialize an array object int[] data = new int[10]; for(int i=0; i<data.length; i++) { data[i] = (int)(Math.random()*101); }

try { fout = new PrintWriter(new FileWriter(args[0]));

for(int i=0; i<data.length; i++) { fout.print(data[i] + " "); }

fout.close(); } catch(IOException ioe) { System.out.println("Error writing to " +

args[0]); } }}

SAVING DATA TO A TEXT FILE

Write 10 randomly generated (0-100) numbers to a text file where each number is on the same line and separated by a space character.

The command-line arguments are:arg[0] is the name of the file to create

May throw an IOException!

Page 27: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

27

Used for reading text files

Constructor SummaryBufferedReader 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

BUFFEREDREADER

Page 28: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

28

import java.io.*;

class ArrayReader { public static void main(String[] args) { BufferedReader fin = null; String line; int[] data = new int[10];

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); }}

READING DATA FROM A TEXT FILE

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

Page 29: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

29

import java.io.*;import java.util.*;

class ArrayReader { public static void main(String[] args) { BufferedReader fin = null; String line; int[] data = new int[10];

try { fin = new BufferedReader(new FileReader(args[0])); for(int i=0; i<10; i++) { data[i] = Integer.valueOf(fin.readLine()).intValue(); / /

C o n v e r t S t r i n g t o i n t } 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); }}

READING DATA FROM A TEXT FILE

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

Page 30: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

30

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 exception3. Place a sentinal value at the end of a file and test for it

DETECTING THE END OF A FILE

Page 31: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

31

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

TESTING FOR END OF FILEIN A TEXT FILE

Page 32: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

32

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); } }}

USING READLINE() FOR LINE-BY-LINE FILE PROCESSING

When using readLine

test for null

readLine throws an IOException

Page 33: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

33

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); } }}

USING READ() FOR CHARACTER-BY-CHARACTER FILE PROCESSING

When using readtest for -1

read throws an IOException

Page 34: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

34

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];

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); }}

READING DATA FROM A TEXT FILE

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

Page 35: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

35

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;

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 maximum value int min = 0; // index of the minimum value int total = 0; // cumulative total for(int i=0; i<count; 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) count); }}

READING DATA FROM A TEXT FILE

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

Page 36: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

36

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;

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 maximum value int min = 0; // index of the minimum value int total = 0; // cumulative total for(int i=0; i<count; 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)count); }}

READING DATA FROM A TEXT FILE

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

Ouch…What do I do!!?!

Page 37: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

37

There are BufferedReader methods to read a line and a character, but not just a single word

StringTokenizer can be used to parse a line into words it is in the java.util library must use “import java.util.*;” you can specify delimiters A delimiter is any character that separates words Default delimiters are the "white space" characters:

space (‘ ‘) tab (‘\t’) newline (‘\n’)

WORD-BY-WORD PROCESSING

Page 38: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

38

The constructor take a String as a formal parameter and uses the default delimiters. Alternatively you may specify the delimiters using a String

as the second parameter.The method hasMoreTokens() returns true if there are

more tokens (words) in the tokenizer and false otherwise

The method nextToken() returns a String that is the next token in the tokenizer

The original string is unchanged.

STRING TOKENIZER

Page 39: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

39

StringTokenizerclass TokenizerDemo {

public static void main(String[] args) {StringTokenizer tok = new StringTokenizer(args[0]);while(tok.hasMoreTokens()) {

System.out.println(tok.nextToken());}

}}

java TokenizerDemo “Testing..1..2..3”java TokenizerDemo “Once upon a time”java TokenizerDemo “1 2 3 4 5 6 7 8”

java TokenizerDemo “1-2-3-4-5-6-7-8”

Page 40: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

40

StringTokenizerclass TokenizerDemo {

public static void main(String[] args) {StringTokenizer tok = new StringTokenizer(args[0], args[1]);while(tok.hasMoreTokens()) {

System.out.println(tok.nextToken());}

}}

java TokenizerDemo “Testing..1..2..3” “.”java TokenizerDemo “Testing..1..2..3” “t.1”java TokenizerDemo “1 2 3 4 5 6 7 8” “12345678”

java TokenizerDemo “1-2-3-4-5-6-7-8” “-”

Page 41: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

41

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;

try { fin = new BufferedReader(new FileReader(filename)); line = fin.readLine(); StringTokenizer tok = new StringTokenizer(line); while(tok.hasMoreTokens()) {

data[count++] = Integer.parseInt(tok.nextToken()); } 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<count; 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)count); }}

READING DATA FROM A TEXT FILE

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

Page 42: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

42

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;

try { fin = new BufferedReader(new FileReader(filename)); while((line = fin.readLine()) != null) { StringTokenizer tok = new StringTokenizer(line); while(tok.hasMoreTokens()) { data[count++] = Integer.parseInt(tok.nextToken()); } } fin.close(); } catch(IOException ioe) { 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); }}

READING DATA FROM A TEXT FILE

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

Page 43: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

43

The most common stream classes for binary 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

BINARY FILES

Page 44: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

44

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

DATAOUTPUTSTREAM METHOD SUMMARY

Page 45: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

45

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 different 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

WHAT IS UTF??

Page 46: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

46

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?

OPENING AN OUTPUT FILE

Page 47: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

47

import java.io.*;

class ArrayWriter { public static void main(String[] args) { DataOutputStream fout = null;

// create and initialize an array object int[] data = new int[10]; for(int i=0; i<data.length; i++) { data[i] = (int)(Math.random()*101); }

try { fout = new DataOutputStream(new FileOutputStream(args[0]));

for(int i=0; i<data.length; i++) { fout.writeInt(data[i]); }

fout.close(); } catch(IOException ioe) { System.out.println("Error writing to " + args[0]); } }}

SAVING DATA TO A BINARY FILE

Write 10 int values to a binary file. Each number is randomly generated in the interval [0..100].

The command-line arguments are:arg[0] is the name of the file to create

Page 48: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

48

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

DATAINPUTSTREAM METHODS

Page 49: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

49

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();

OPENING AN OUTPUT FILE

Page 50: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

50

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

INPUT FILE EXCEPTIONS

Page 51: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

51

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

AVOIDING COMMON DATAINPUTSTREAM FILE ERRORS

Page 52: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

52

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

THE EOFEXCEPTION CLASS

Page 53: Input and Output FILE IO. 2  I/O stands for Input/Output  In this context it is input to and output from programs  Input can be from the keyboard or

53

USING EOFEXCEPTION

Note order of catch blocks:the most specific is firstand the most general last

try { DataInputStream inputStream =

new DataInputStream(new FileInputStream("numbers.dat")); int n; 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.");}

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

Problem: Write code to print the values in a binary file named “numbers.dat” which contains zero or more int values.