Chapter 2 Input Output New

99
Chapter 2 Chapter 2 Java I/O Ch-2 Advanced Programming 1

Transcript of Chapter 2 Input Output New

Page 1: Chapter 2 Input Output New

Chapter 2Chapter 2Java I/OCh-2 Advanced

Programming

1

Page 2: Chapter 2 Input Output New

Topics

0 Stream0 File I/O 0 Byte stream0 Character Stream0 Buffered Stream

Ch-2 Advanced Programming 2

Page 3: Chapter 2 Input Output New

Input/Output Basics0Input/Output = I/O = communication between

a computer program and external sources and destinations of information

0Involves Reading and Writing0 Reading input from a source0 Writing output to a destination

0Example Sources and Destinations:0 Files0 Network connections0 Other programsCh-2 Advanced Programming 3

Page 4: Chapter 2 Input Output New

Understanding Streams0A stream 'is' a sequence of bytes 0When writing data to a stream, the stream is called an

output stream. 0When reading data from a stream, the stream is called an

input stream. 0If a stream has a buffer in memory, it is a buffered

stream. 0Binary Streams contain binary data. 0Character Streams have character data and are used for

storing and retrieving text

Ch-2 Advanced Programming 4

Class Description

InputStream The base class for byte stream input operations.

OutputStream The base class for byte stream output operations.

BufferedInputStream Buffers input from another stream in memory to make the read operations more efficient.

Page 5: Chapter 2 Input Output New

Understanding Streams(cont)0Java uses an I/O system called streams (pioneered in C++)0Java provides java.io package to implement streams0Streams treat all external source and destinations of data

the same way: as "streams" of information0A stream is a sequence of data of undetermined length.

There's no definite end to it. 0In Java a stream is composed of discrete bytes. The bytes

may represent chars or other kinds of data. They may come faster than you can handle them, or your thread may block while waiting for the next one to arrive.

0The key to processing the stream is a while loop that processes each piece of data, until you encounter the end-of-stream character or some other exceptional condition occurs.

Ch-2 Advanced Programming 5

Page 6: Chapter 2 Input Output New

Input vs. Output Streams

0Reading from an Input Stream

0Writing to an Output Stream

Ch-2 Advanced Programming 6

Page 7: Chapter 2 Input Output New

Byte vs. Character Streams0 All data and programs are ultimately just zeros and ones

0 each digit can have one of two values, hence binary0 bit is one binary digit0 byte is a group of eight bits

0 Text files: the bits represent printable characters0 one byte per character for ASCII, the most common code0 for example, Java source files are text files0 so is any file created with a "text editor"

0 Binary files: the bits represent other types of encoded information, such as executable instructions or numeric data0 these files are easily read by the computer but not humans0 they are not "printable" files

0actually, you can print them, but they will be unintelligible0"printable" means "easily readable by humans when printed"

Ch-2 Advanced Programming 7

Page 8: Chapter 2 Input Output New

Byte vs. Character Streams

0Byte Streams are used to read and write data in binary format (1's and 0's)

example data: images, sounds, executable programs, word-processing documents, etc.

0Character Streams are used to read and write data in text format (characters)

example data: plain text files (txt extension), web pages, user keyboard input, etc.

Ch-2 Advanced Programming 8

Page 9: Chapter 2 Input Output New

Java Classes

0Package java.io offers classes to connect to streams

0To connect to a stream, instantiate a subclass of one of these abstract superclasses:

input outputbyte InputStream OutputStreamcharacter Reader Writer

Ch-2 Advanced Programming 9

Page 10: Chapter 2 Input Output New

Java: Text Versus Binary Files

0 Text files are more readable by humans0 Binary files are more efficient

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

0 they can be used by Java on different machines0 Reading and writing binary files is normally done by a program0 text files are 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

Ch-2 Advanced Programming 10

Page 11: Chapter 2 Input Output New

Text Files vs. Binary Files

0 Number: 127 (decimal)0 Text file

0Three bytes: “1”, “2”, “7”0ASCII (decimal): 49, 50, 550ASCII (octal): 61, 62, 670ASCII (binary): 00110001, 00110010, 00110111

0 Binary file: 0One byte (byte): 01111110 0Two bytes (short): 00000000 011111100Four bytes (int): 00000000 00000000 00000000

01111110

Ch-2 Advanced Programming 11

Page 12: Chapter 2 Input Output New

Text File I/O

0 Important classes for text file output (to the file)0 PrintWriter0 FileOutputStream [or FileWriter]

0 Important classes for text file input (from the file):0 BufferedReader0 FileReader

0 FileOutputStream and FileReader take file names as arguments.0 PrintWriter and BufferedReader provide useful methods for

easier writing and reading.0 Usually need a combination of two classes0 To use these classes your program needs a line like the following:

import java.io.*;

Ch-2 Advanced Programming 12

Page 13: Chapter 2 Input Output New

Why Buffering?

0 Not buffered: each byte is read/written from/to disk as soon as possible0 “little” delay for each byte 0 A disk operation per byte---higher overhead

0 Buffered: reading/writing in “chunks”0 Some delay for some bytes

0Assume 16-byte buffers0Reading: access the first 4 bytes, need to wait for all 16

bytes are read from disk to memory0Writing: save the first 4 bytes, need to wait for all 16 bytes

before writing from memory to disk0 A disk operation per a buffer of bytes---lower overhead

Ch-2 Advanced Programming 13

Page 14: Chapter 2 Input Output New

Every File Has Two Names

1. the stream name used by Java0 outputStream in the example

2. the name used by the operating system0 out.txt in the example

Ch-2 Advanced Programming 14

Page 15: Chapter 2 Input Output New

Text File Output0 To open a text file for output: connect a text file to a stream for writing

PrintWriter outputStream =new PrintWriter(new FileOutputStream("out.txt"));

0 Similar to the long way:

FileOutputStream s = new FileOutputStream("out.txt");PrintWriter outputStream = new PrintWriter(s);

0 Goal: create a PrintWriter object0 which uses FileOutputStream to open a text file

0 FileOutputStream “connects” PrintWriter to a text file.

Ch-2 Advanced Programming 15

Page 16: Chapter 2 Input Output New

Output File Streams

PrintWriter FileOutputStream

DiskMemory

outputStream out.txt

PrintWriter smileyOutStream = new PrintWriter( new FileOutputStream(“smiley.txt”) );

Ch-2 Advanced Programming 16

Page 17: Chapter 2 Input Output New

Methods for PrintWriter0 Similar to methods for System.out0 println

outputStream.println(count + " " + line);

0 print0 format0 flush: write buffered output to disk0 close: close the PrintWriter stream (and file)

Ch-2 Advanced Programming 17

Page 18: Chapter 2 Input Output New

TextFileOutputDemoPart 1

public static void main(String[] args){ PrintWriter outputStream = null; try { outputStream = new PrintWriter(new FileOutputStream("out.txt"));

} catch(FileNotFoundException e) { System.out.println("Error opening the file out.txt. “ + e.getMessage()); System.exit(0); }

A try-block is a block:outputStream would not be accessible to the rest of the method if it were declared inside the try-block

Creating a file can cause the FileNotFound-Exception if the new file cannot be made.

Opening the file

Ch-2 Advanced Programming 18

Page 19: Chapter 2 Input Output New

TextFileOutputDemoPart 2

Scanner keyboard = new Scanner(System.in);System.out.println("Enter three lines of text:");String line = null;int count; for (count = 1; count <= 3; count++) { line = keyboard.nextLine(); outputStream.println(count + " " + line); } outputStream.close(); System.out.println("... written to out.txt.");}

The println method is used with two different streams: outputStream and System.out

Closing the file

Writing to the file

Ch-2 Advanced Programming 19

Page 20: Chapter 2 Input Output New

Writers(Another method)0Writer is an abstract class to write to character

streams

0Offers write methods to write single characters, arrays of characters, and stringsvoid write(int c)void write(char cbuf[])void write(String str)

0BufferedWriter offers efficient writing and a newLine() method to insert a blank line

0Close writers with close() method when doneCh-2 Advanced Programming 20

Page 21: Chapter 2 Input Output New

How to Write to a Text Filepublic void writeFileWithBufferedWriter() { BufferedWriter buffWriter = null; try { FileWriter fw = new FileWriter("output.txt"); buffWriter = new BufferedWriter(fw); while (/*still stuff to write */) { String line = // get line to write buffWriter.write(line); buffWriter.newLine(); } } catch (IOException e) { System.out.println("Error writing to file"); } if (buffWriter != null) { try { buffWriter.close(); } catch(IOException e) { /* ignore */ } }}

Ch-2 Advanced Programming 21

Page 22: Chapter 2 Input Output New

Overwriting a File

0 Opening an output file creates an empty file

0 Opening an output file creates a new file if it does not already exist

0 Opening an output file that already exists eliminates the old file and creates a new, empty one0 data in the original file is lost

0 To see how to check for existence of a file, see the section of the text that discusses the File class (later slides).

Ch-2 Advanced Programming 22

Page 23: Chapter 2 Input Output New

Java Tip: Appending to a Text File

0 To add/append to a file instead of replacing it, use a different constructor for FileOutputStream:

outputStream =new PrintWriter(new FileOutputStream("out.txt", true));

0 Second parameter: append to the end of the file if it exists?0 Sample code for letting user tell whether to replace or append:

System.out.println("A for append or N for new file:");char ans = keyboard.next().charAt(0);boolean append = (ans == 'A' || ans == 'a');outputStream = new PrintWriter(

new FileOutputStream("out.txt", append));

true if user enters 'A'

Ch-2 Advanced Programming 23

Page 24: Chapter 2 Input Output New

Closing a File0 An output file should be closed when you are done

writing to it (and an input file should be closed when you are done reading from it).

0 Use the close method of the class PrintWriter (BufferedReader also has a close method).

0 For example, to close the file opened in the previous example:

outputStream.close();0 If a program ends normally it will close any files that are

open.Ch-2 Advanced Programming 24

Page 25: Chapter 2 Input Output New

FAQ: Why Bother to Close a File?

If a program automatically closes files when it ends normally, why close them with explicit calls to close?

Two reasons:

1. To make sure it is closed if a program ends abnormally (it could get damaged if it is left open).

2. A file opened for writing must be closed before it can be opened for reading.

0Although Java does have a class that opens a file for both reading and writing, it is not used in this text.

Ch-2 Advanced Programming 25

Page 26: Chapter 2 Input Output New

Text File Input0 To open a text file for input: connect a text file to a stream for reading

0 Goal: a BufferedReader object, 0which uses FileReader to open a text file

0 FileReader “connects” BufferedReader to the text file0 For example:

BufferedReader smileyInStream = new BufferedReader(new FileReader(“smiley.txt"));

0 Similarly, the long way:FileReader s = new FileReader(“smiley.txt");BufferedReader smileyInStream = new BufferedReader(s);

Ch-2 Advanced Programming 26

Page 27: Chapter 2 Input Output New

Input File Streams

BufferedReader FileReader

DiskMemory

smileyInStream smiley.txt

BufferedReader smileyInStream = new BufferedReader( new FileReader(“smiley.txt”) );

Ch-2 Advanced Programming 27

Page 28: Chapter 2 Input Output New

Using a Reader0Recall: a Reader is used to read a character input stream

0Reader offers these methods to read single characters and arrays of characters:int read()

int read(char cbuf[]) int read(char cbuf[], int offset, int length)

0Reader is abstract so you must instantiate a subclass of it to use these methods

0The basic read() method reads a single unsigned byte of data and returns the int value of the unsigned byte. This is a number between 0 and 255.

0If the end of stream is encountered, it returns -1 instead; and you can use this as a flag to watch for the end of stream.

Ch-2 Advanced Programming 28

Page 29: Chapter 2 Input Output New

How to Read from a Text Filepublic void readFile() { FileReader fileReader = null; try { fileReader = new FileReader("input.txt");

int c = fileReader.read(); while (c != -1) { // cast c to char and use it c = fileReader.read(); } } catch (FileNotFoundException e) { System.out.println("File was not found"); } catch (IOException e) { System.out.println("Error reading from file"); } if (fileReader != null) { try { fileReader.close(); } catch (IOException e) { /* ignore */ } }} Ch-2 Advanced Programming 29

Page 30: Chapter 2 Input Output New

Methods for BufferedReader

0readLine: read a line into a String0 no methods to read numbers directly, so read

numbers as Strings and then convert them (StringTokenizer later)

0read: read a char at a time0close: close BufferedReader stream

Ch-2 Advanced Programming 30

Page 31: Chapter 2 Input Output New

Exception Handling with File I/O

Catching IOExceptions0 IOException is a predefined class0 File I/O might throw an IOException0 catch the exception in a catch block that at least prints an error message

and ends the program0 FileNotFoundException is derived from IOException

0 therefor any catch block that catches IOExceptions also catches FileNotFoundExceptions

0 put the more specific one first (the derived one) so it catches specifically file-not-found exceptions

0 then you will know that an I/O error is something other than file-not-found

Ch-2 Advanced Programming 31

Page 32: Chapter 2 Input Output New

Example:Reading a File Name from the

Keyboard

public static void main(String[] args) { String fileName = null; // outside try block, can be used in catch try { Scanner keyboard = new Scanner(System.in); System.out.println("Enter file name:"); fileName = keyboard.next(); BufferedReader inputStream = new BufferedReader(new FileReader(fileName)); String line = null; line = inputStream.readLine(); System.out.println("The first line in " + filename + " is:"); System.out.println(line); // . . . code for reading second line not shown here . . . inputStream.close(); } catch(FileNotFoundException e) { System.out.println("File " + filename + " not found."); } catch(IOException e) { System.out.println("Error reading from file " + fileName); } }

Chapter 10 Java: an Introduction to Computer Science & Programming - Walter Savitch 32

reading a file name from the keyboard

closing the file

using the file name read from the keyboard

reading data from the file

Ch-2 Advanced Programming 32

Page 33: Chapter 2 Input Output New

Wrap in a BufferedReader0BufferedReader has a readLine() method to

read an entire line of characters efficiently

0Wrap a Reader with a BufferedReader by passing the Reader as a constructor argument

FileReader fr = new FileReader("myFile.txt"); BufferedReader br = new BufferedReader(fr);

0The readLine() method returns null when there are no more lines to read

Ch-2 Advanced Programming 33

Page 34: Chapter 2 Input Output New

Using BufferedReaderpublic void readFileWithBufferedReader() { BufferedReader bufferedReader = null; try { FileReader fr = new FileReader("input.txt"); bufferedReader = new BufferedReader(fr);

String line = bufferedReader.readLine(); while (line != null) { // do something with line line = bufferedReader.readLine(); } } catch (FileNotFoundException e) { System.out.println("File was not found"); } catch (IOException e) { System.out.println("Error reading from file"); } if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { /* ignore */ } } } Ch-2 Advanced Programming 34

Page 35: Chapter 2 Input Output New

Exception.getMessage()try{ …}catch (FileNotFoundException e){ System.out.println(filename + “ not found”); System.out.println(“Exception: “ + e.getMessage()); System.exit(-1);}

Ch-2 Advanced Programming 35

Page 36: Chapter 2 Input Output New

Example: StringTokenizer0 Display the words separated by any of the following characters:

space, new line (\n), period (.) or comma (,).

String inputLine = keyboard.nextLine();StringTokenizer wordFinder = new StringTokenizer(inputLine, " \n.,");//the second argument is a string of the 4 delimiterswhile(wordFinder.hasMoreTokens()){ System.out.println(wordFinder.nextToken());}

Question2bor!tooBee

Entering "Question,2b.or !tooBee." gives this output:

Ch-2 Advanced Programming 36

Page 37: Chapter 2 Input Output New

Reading Words in a String:Using StringTokenizer Class

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

0 StringTokenizer can be used to parse a line into words0 import java.util.*0 some of its useful methods are shown in the text

0e.g. test if there are more tokens0 you can specify delimiters (the character or characters that

separate words)0 the default delimiters are "white space" (space, tab, and

newline)

Ch-2 Advanced Programming 37

Page 38: Chapter 2 Input Output New

Delimiters0 When data is stored in text format, delimiter characters

are used to separate tokens of the data

0 A list of first names stored separated by the '#' delimiter: Abera#Tase#Gobena#Biritu

0 Same list with a newline delimiter:

AberaTaseGobenaBiritu

Ch-2 Advanced Programming 38

Page 39: Chapter 2 Input Output New

StringTokenizer0java.util.StringTokenizer separates Strings at the delimiters to extract tokens

0Default constructor will assume any whitespace (spaces, tabs, newlines) to be delimiters

0Second constructor accepts String of any delimiter characters

0nextToken method returns the next data token between delimiters in the text

0hasMoreTokens returns true if the text has remaining tokens

Ch-2 Advanced Programming 39

Page 40: Chapter 2 Input Output New

Using StringTokenizer0 Printing out every name from a file where names are

delimited by #:

public void printNamesFromFile(String filename) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(filename)); String line = br.readLine(); while(line != null) { StringTokenizer st = new StringTokenizer(line); while(st.hasMoreTokens()) { System.out.println(st.nextToken(“#”)); } line = br.readLine(); } } catch (IOException e) { System.out.println("Error reading from file."); } if (br != null) { try { br.close(); } catch(IOException e) {} }} Ch-2 Advanced Programming

40

Page 41: Chapter 2 Input Output New

Putting it All Together0File 1: Employee_May.dat Format: Name, SSN, Hourly Rate, Salary to Date Paul Njoroge, 555-12-3456, 65, 20000 Evelyn Eastmond, 555-22-2222, 70, 30000 Peilei Fan, 555-33-4444, 60, 15000 Ethan Howe, 555-44-5555, 80, 40000 Naveen Goela, 555-66-8888, 75, 20000 . . .

0File 2: Hours_June.dat Format: Consecutive integers, which are the number of hours

each employee has worked during June. The integers have the same sequence as that of the employee records. Content: 50 60 40 50 70 . . .

Ch-2 Advanced Programming 41

Page 42: Chapter 2 Input Output New

What We Need to Do . . .1. For each employee, multiply the hours worked by the

hourly rate

2. Add this to the value of the salary to date

3. Write to a new file named Employee_June.dat, in the same format as Employee_May.dat, only it includes the updated, increased value of the salary to date.

Ch-2 Advanced Programming 42

Page 43: Chapter 2 Input Output New

Create a StringTokenizer over the single line in the Hours_June.dat file

BufferedReader empReader = null;String hoursLine = null;try { empReader = new BufferedReader( new FileReader("Hours_June.dat")); hoursLine = empReader.readLine();} catch(IOException e) { System.out.println("Could not read Hours_June.dat");}

if (empReader != null) { try { empReader.close(); } catch(IOException e) {}}

if (line == null) // exit and report an errorStringTokenizer hoursST = new StringTokenizer(hoursLine);

Ch-2 Advanced Programming 43

Page 44: Chapter 2 Input Output New

BufferedReader mayReader = null;BufferedWriter juneWriter = null;try { mayReader = new BufferedReader( new FileReader("Employee_May.dat")); juneWriter = new BufferedWriter( new FileWriter("Employee_June.dat"));

// On next slide, we add code to parse the May data, // do the salary calculation, and write the June data

} catch(IOException e) { System.out.println("Error with employee files");}if (mayReader != null) { try { mayReader.close(); } catch(IOException e) {}}if (juneWriter != null) { try { juneWriter.close(); } catch(IOException e) {}}

Opening and closing the streams to the employee files

Ch-2 Advanced Programming

44

Page 45: Chapter 2 Input Output New

Testing for End of File in a Text File

0 When readLine tries to read beyond the end of a text file it returns the special value null0 so you can test for null to stop processing a text file

0 read returns -1 when it tries to read beyond the end of a text file0 the int value of all ordinary characters is nonnegative

0 Neither of these two methods (read and readLine) will throw an EOFException.

Ch-2 Advanced Programming 45

Page 46: Chapter 2 Input Output New

int count = 0; String line = inputStream.readLine(); while (line != null) { count++; outputStream.println(count + " " + line); line = inputStream.readLine(); }

Chapter 9 Java: an Introduction to Computer Science & Programming - Walter Savitch 46

Excerpt from TextEOFDemo

Example: Using Null toTest for End-of-File in a Text File

When using readLinetest for null

When using read test for -1Ch-2 Advanced Programming 46

Page 47: Chapter 2 Input Output New

Using Path Names0 Path name—gives name of file and tells which directory the file is

in0 Relative path name—gives the path starting with the directory

that the program is in0 Typical UNIX path name:

/user/smith/home.work/java/FileClassDemo.java0 Typical Windows path name:

D:\Work\Java\Programs\FileClassDemo.java0 When a backslash is used in a quoted string it must be written as

two backslashes since backslash is the escape character:

"D:\\Work\\Java\\Programs\\FileClassDemo.java"0 Java will accept path names in UNIX or Windows format, regardless

of which operating system it is actually running on.Ch-2 Advanced Programming 47

Page 48: Chapter 2 Input Output New

File Class [java.io]0 Acts like a wrapper class for file names0 A file name like "numbers.txt" has only String properties0 File has some very useful methods

0 exists: tests if a file already exists0 canRead: tests if the OS will let you read a file0 canWrite: tests if the OS will let you write to a file0 delete: deletes the file, returns true if successful0 length: returns the number of bytes in the file0 getName: returns file name, excluding the preceding path0 getPath: returns the path name—the full name

File numFile = new File(“numbers.txt”); if (numFile.exists()) System.out.println(numfile.length());

Ch-2 Advanced Programming 48

Page 49: Chapter 2 Input Output New

File Objects and Filenames

0 FileInputStream and FileOutputStream have constructors that take a File argument as well as constructors that take a String argument

PrintWriter smileyOutStream = new PrintWriter(new FileOutputStream(“smiley.txt”));

File smileyFile = new File(“smiley.txt”);if (smileyFile.canWrite()) PrintWriter smileyOutStream = new PrintWriter(new FileOutputStream(smileyFile));

Ch-2 Advanced Programming 49

Page 50: Chapter 2 Input Output New

Alternative with Scanner0 Instead of BufferedReader with FileReader, then StringTokenizer

0 Use Scanner with File:Scanner inFile = new Scanner(new File(“in.txt”));0 Similar to Scanner with System.in:Scanner keyboard = new Scanner(System.in);

Ch-2 Advanced Programming 50

Page 51: Chapter 2 Input Output New

Reading in int’s

Scanner inFile = new Scanner(new File(“in.txt"));int number;while (inFile.hasInt()) { number = inFile.nextInt(); // …

}

Ch-2 Advanced Programming 51

Page 52: Chapter 2 Input Output New

Reading in lines of characters

Scanner inFile = new Scanner(new File(“in.txt"));String line;while (inFile.hasNextLine()) { line = inFile.nextLine(); // …

}

Ch-2 Advanced Programming 52

Page 53: Chapter 2 Input Output New

Multiple types on one line// Name, id, balance Scanner inFile = new Scanner(new File(“in.txt"));while (inFile.hasNext()) { name = inFile.next(); id = inFile.nextInt(); balance = inFile.nextFloat(); // … new Account(name, id, balance); }--------------------String line;while (inFile.hasNextLine()) {

line = inFile.nextLine(); Scanner parseLine = new Scanner(line) // Scanner again!

name = parseLine.next(); id = parseLine.nextInt(); balance = parseLine.nextFloat(); // … new Account(name, id, balance); }

Ch-2 Advanced Programming 53

Page 54: Chapter 2 Input Output New

Multiple types on one line// Name, id, balance Scanner inFile = new Scanner(new File(“in.txt"));String line;while (inFile.hasNextLine()) { line = inFile.nextLine(); Account account = new Account(line);

}--------------------public Account(String line) // constructor{ Scanner accountLine = new Scanner(line); _name = accountLine.next(); _id = accountLine.nextInt(); _balance = accountLine.nextFloat();}

Ch-2 Advanced Programming 54

Page 55: Chapter 2 Input Output New

BufferedReader vs Scanner(parsing primitive types)

0Scanner0 nextInt(), nextFloat(), … for parsing types

0BufferedReader0 read(), readLine(), … none for parsing types0 needs StringTokenizer then wrapper class

methods like Integer.parseInt(token)

Ch-2 Advanced Programming 55

Page 56: Chapter 2 Input Output New

BufferedReader vs Scanner(Checking End of File/Stream (EOF))

0BufferedReader0 readLine() returns null0 read() returns -1

0Scanner0 nextLine() throws exception0 needs hasNextLine() to check first0 nextInt(), hasNextInt(), …

Ch-2 Advanced Programming 56

Page 57: Chapter 2 Input Output New

BufferedReader inFile = …line = inFile.readline();while (line != null){ // … line = inFile.readline();}

-------------------

Scanner inFile = …while (inFile.hasNextLine()){ line = infile.nextLine(); // …}

Ch-2 Advanced Programming 57

Page 58: Chapter 2 Input Output New

BufferedReader inFile = …line = inFile.readline();while (line != null){ // … line = inFile.readline();}

-------------------

BufferedReader inFile = …while ((line = inFile.readline()) != null){ // …}

Ch-2 Advanced Programming 58

Page 59: Chapter 2 Input Output New

My suggestion

0 Use Scanner with File0 new Scanner(new File(“in.txt”))

0 Use hasNext…() to check for EOF0 while (inFile.hasNext…())

0 Use next…() to read0 inFile.next…()

0 Simpler and you are familiar with methods for Scanner

Ch-2 Advanced Programming 59

Page 60: Chapter 2 Input Output New

My suggestion cont…0 File input

0Scanner inFile = new Scanner(new File(“in.txt”));

0 File output0PrintWriter outFile = new PrintWriter(new File(“out.txt”));0 outFile.print(), println(), format(), flush(), close(), …

Ch-2 Advanced Programming 60

Page 61: Chapter 2 Input Output New

Example: Copying Text Filesvoid copyFiles(String inFilename, String outFilename) throws FileNotFoundException { BufferedReader br = null; BufferedWriter bw = null; try { br = new BufferedReader(new FileReader(inFilename)); bw = new BufferedWriter(new FileWriter(outFilename)); String line = br.readLine(); while(line != null) { bw.write(line); bw.newLine(); line = br.readLine(); } } catch (IOException e) { System.out.println("Error copying files"); }

if (br != null) {try {br.close();} catch(IOException e) {}} if (bw != null) {try {bw.close();} catch(IOException e) {}}} Ch-2 Advanced Programming 61

Page 62: Chapter 2 Input Output New

Example: Scanning for a Virus

0 What is a virus?0 software that hides itself within other executable

programs0 that executable program is the "host" for the virus0 the virus program tries to "infect" other programs0 the virus can cause problems that range from annoying

to malicious0 A virus that prints an annoying message stores that

string value within itself0 we will write a program that searches through a file to

find that text, or signature

Ch-2 Advanced Programming 62

Page 63: Chapter 2 Input Output New

Virus-Detection Algorithm

1. Repeat the following:a) read a line from a file

b) if no line read due to EOF, terminate

c) otherwise scan the line for specified string of text

d) if that text found(eg. Malware ), stop reading from file

2. Display message whether or not target string was found – signifying virus found/not found

Ch-2 Advanced Programming 63

Page 64: Chapter 2 Input Output New

Other methodsOther methods

Ch-2 Advanced

Programming

64

Page 65: Chapter 2 Input Output New

Rename a file or directory

0 Use renameTo(File path) to rename a file

import java.io.File;public class MainClass {

public static void main(String[] a) {File file = new File("c:\\text.txt");file.renameTo(new File("c:\\

anotherText.txt"));}

}

Ch-2 Advanced Programming 65

Page 66: Chapter 2 Input Output New

Creates a directory

0 Use mkdir(): to create a directory

import java.io.File;public class MainClass {

public static void main(String[] a) {File file = new File("c:\\NewFolder\\");file.mkdir();

}}

Ch-2 Advanced Programming 66

Page 67: Chapter 2 Input Output New

Creates a directory including any parent directories

0 Use mkdirs(): to create any parent directories

0 import java.io.File;public class MainClass {

public static void main(String[] a) {File file = new File("c:\\Parent\\Sub\\");file.mkdirs();

}}

Ch-2 Advanced Programming 67

Page 68: Chapter 2 Input Output New

Construct file path

import java.io.File;

public class Main {

public static void main(String[] args) {String filePath = File.separator + "Java" + File.separator + "IO";File file = new File(filePath);System.out.println(file.getPath());

}}// \Java\IO

Ch-2 Advanced Programming 68

Page 69: Chapter 2 Input Output New

Absolute and Relative Paths

0 import java.io.File;public class MainClass {

public static void main(String[] a) {File myFile = new File("output.txt");System.out.println(myFile.getAbsolutePath());

}}

0 Ouput

C:\Java_Dev\eclipse31\Apache Common\output.txt

Ch-2 Advanced Programming 69

Page 70: Chapter 2 Input Output New

delete the file or directory0 Use delete(): to delete the file or directory

0 import java.io.File;public class MainClass {

public static void main(String[] a) {File file = new File("c:\\test\\test.txt");boolean success = file.delete();System.out.println(success);

}}

Ch-2 Advanced Programming 70

Page 71: Chapter 2 Input Output New

delete file or directory when the program ends

0 Use deleteOnExit(): to delete file or directory when the program ends

0 import java.io.File;public class MainClass {

public static void main(String[] a) {File file = new File("c:\\test\\test.txt");file.deleteOnExit();

}}

Ch-2 Advanced Programming 71

Page 72: Chapter 2 Input Output New

List all roots0 import java.io.File;

public class SpaceChecker {public static void main(String[] args) { File[] roots = File.listRoots();

for (int i = 0; i < roots.length; i++) {System.out.println(roots[i]);System.out.println("Free space = " + roots[i].getFreeSpace());System.out.println("Usable space = " + roots[i].getUsableSpace());System.out.println("Total space = " + roots[i].getTotalSpace());

System.out.println(); } }}

Ch-2 Advanced Programming 72

C:\Free space = 30522142720Usable space = 30522142720Total space = 112160927744

D:\Free space = 22253076480Usable space = 22253076480Total space = 254930841600

E:\Free space = 0Usable space = 0Total space = 0

Page 73: Chapter 2 Input Output New

Use RandomAccessFile to reverse a file

0 import java.io.RandomAccessFile;

public class Main {public static void main(String[] argv) throws Exception {

RandomAccessFile raf = new RandomAccessFile("a.dat", "rw");int x, y;

for (long i = 0, j = raf.length() - 1; i < j; i++, j--) {raf.seek(i);x = raf.read();raf.seek(j);y = raf.read();

raf.seek(j);raf.write(x);raf.seek(i);raf.write(y);

} raf.close();}

}Ch-2 Advanced Programming 73

Page 74: Chapter 2 Input Output New

Use RandomAccessFile to reverse a file

0 The value of mode can be one of these:"r". Open for reading only."rw". Open for reading and writing.

If the file does not already exist, RandomAccessFile creates the file.

"rws". Open for reading and writing and require that every update to the file's content and metadata be written synchronously.

"rwd". Open for reading and writing and require that every update to the file's content (but not metadata) be written synchronously.

Ch-2 Advanced Programming 74

Page 75: Chapter 2 Input Output New

Basic Binary File I/O0 Important classes for binary file output (to the file)

0 ObjectOutputStream0 FileOutputStream

0 Important classes for binary file input (from the file):0 ObjectInputStream0 FileInputStream

0 Note that FileOutputStream and FileInputStream are used only for their constructors, which can take file names as arguments.0 ObjectOutputStream and ObjectInputStream cannot take

file names as arguments for their constructors.0 To use these classes your program needs a line like the following:

import java.io.*;

Ch-2 Advanced Programming 75

Page 76: Chapter 2 Input Output New

Java File I/O: Stream Classes0 ObjectInputStream and ObjectOutputStream:

0 have methods to either read or write data one byte at a time0 automatically convert numbers and characters into binary

0binary-encoded numeric files (files with numbers) are not readable by a text editor, but store data more efficiently

0 Remember:0 input means data into a program, not the file0 similarly, output means data out of a program, not the file

Ch-2 Advanced Programming 76

Page 77: Chapter 2 Input Output New

When Using ObjectOutputStreamto Output Data to Files:

0 The output files are binary and can store any of the primitive data types (int, char, double, etc.) and the String type

0 The files created can be read by other Java programs but are not printable

0 The Java I/O library must be imported by including the line:import java.io.*;0 it contains ObjectOutputStream and other useful class

definitions

0 An IOException might be thrown

Ch-2 Advanced Programming 77

Page 78: Chapter 2 Input Output New

Handling IOException0 IOException cannot be ignored

0 either handle it with a catch block0 or defer it with a throws-clause

We will put code to open the file and write to it in a try-block and write a catch-block for this exception :

catch(IOException e){ System.out.println("Problem with output...";}

Ch-2 Advanced Programming 78

Page 79: Chapter 2 Input Output New

Opening a New Output File0 The file name is given as a String

0 file name rules are determined by your operating system

0 Opening an output file takes two steps

1. Create a FileOutputStream object associated with the file name String

2. Connect the FileOutputStream to an ObjectOutputStream object

This can be done in one line of code

Ch-2 Advanced Programming 79

Page 80: Chapter 2 Input Output New

Example: Opening an Output FileTo open a file named numbers.dat:

ObjectOutputStream outputStream = new ObjectOutputStream( new FileOutputStream("numbers.dat"));

0 The constructor for ObjectOutputStream requires a FileOutputStream argument

0 The constructor for FileOutputStream requires a String argument0 the String argument is the output file name

0 The following two statements are equivalent to the single statement above: FileOutputStream middleman =new FileOutputStream("numbers.dat");

ObjectOutputStream outputStream =new ObjectOutputSteam(middleman);

Ch-2 Advanced Programming 80

Page 81: Chapter 2 Input Output New

Some ObjectOutputStream Methods

0 You can write data to an output file after it is connected to a stream class0 Use methods defined in ObjectOutputStream

0writeInt(int n)0writeDouble(double x)0writeBoolean(boolean b)0etc.0See the text for more

0 Note that each write method throws IOException0 eventually we will have to write a catch block for it

0 Also note that each write method includes the modifier final0 final methods cannot be redefined in derived classes

Ch-2 Advanced Programming 81

Page 82: Chapter 2 Input Output New

Closing a File0 An Output file should be closed when you are done

writing to it

0 Use the close method of the class ObjectOutputStream

0 For example, to close the file opened in the previous example:

outputStream.close();

0 If a program ends normally it will close any files that are open

Ch-2 Advanced Programming 82

Page 83: Chapter 2 Input Output New

Writing a Character to a File:an Unexpected Little

Complexity0 The method writeChar has an annoying property:0 it takes an int, not a char, argument

0 But it is easy to fix:0 just cast the character to an int

0 For example, to write the character 'A' to the file opened previously:

outputStream.writeChar((int) 'A');

0 Or, just use the automatic conversion from char to int

Ch-2 Advanced Programming 83

Page 84: Chapter 2 Input Output New

Writing a boolean Value to a File

0boolean values can be either of two values, true or false

0true and false are not just names for the values, they actually are of type boolean

0 For example, to write the boolean value false to the output file:

outputStream.writeBoolean(false);

Ch-2 Advanced Programming 84

Page 85: Chapter 2 Input Output New

Writing Strings to a File:Another Little Unexpected Complexity

0 Use the writeUTF method to output a value of type String0 there is no writeString method

0 UTF stands for Unicode Text Format0 a special version of Unicode

0 Unicode: a text (printable) code that uses 2 bytes per character0 designed to accommodate languages with a different alphabet or no

alphabet (such as Chinese and Japanese)0 ASCII: also a text (printable) code, but it uses just 1 byte per character

0 the most common code for English and languages with a similar alphabet

0 UTF is a modification of Unicode that uses just one byte for ASCII characters0 allows other languages without sacrificing efficiency for ASCII files

Ch-2 Advanced Programming 85

Page 86: Chapter 2 Input Output New

When Using ObjectInputStream to Read Data from Files:

0 Input files are binary and contain any of the primitive data types (int, char, double, etc.) and the String type

0 The files can be read by Java programs but are not printable

0 The Java I/O library must be imported including the line:import java.io.*;0 it contains ObjectInputStream and other useful class

definitions

0 An IOException might be thrown

Ch-2 Advanced Programming 86

Page 87: Chapter 2 Input Output New

Opening a New Input File0 Similar to opening an output file, but replace "output" with "input"

0 The file name is given as a String0 file name rules are determined by your operating system

0 Opening a file takes two steps

1. Creating a FileInputStream object associated with the file name String

2. Connecting the FileInputStream to an ObjectInputStream object

0 This can be done in one line of codeCh-2 Advanced Programming 87

Page 88: Chapter 2 Input Output New

Example: Opening an Input File

To open a file named numbers.dat:

ObjectInputStream inStream =new ObjectInputStream (new FileInputStream("numbers.dat"));

0 The constructor for ObjectInputStream requires a FileInputStream argument

0 The constructor for FileInputStream requires a String argument0 the String argument is the input file name

0 The following two statements are equivalent to the statement at the top of this slide:

FileInputStream middleman =new FileInputStream("numbers.dat");

ObjectInputStream inputStream =new ObjectInputStream (middleman);Ch-2 Advanced Programming 88

Page 89: Chapter 2 Input Output New

Some ObjectInputStream Methods

0 For every output file method there is a corresponding input file method

0 You can read data from an input file after it is connected to a stream class0 Use methods defined in ObjectInputStream

0readInt()0readDouble()0readBoolean()0etc.0See the text for more

0 Note that each write method throws IOException

0 Also note that each write method includes the modifier finalCh-2 Advanced Programming 89

Page 90: Chapter 2 Input Output New

Input File Exceptions

0 A FileNotFoundException is thrown if the file is not found when an attempt is made to open a file

0 Each read method throws IOException0 we still have to write a catch block for it

0 If a read goes beyond the end of the file an EOFException is thrown

Ch-2 Advanced Programming 90

Page 91: Chapter 2 Input Output New

Avoiding Common ObjectInputStream File Errors

There is no error message (or exception)

if you read the wrong data type!

0 Input files can contain a mix of data types0 it is up to the programmer to know their order and use

the correct read method0ObjectInputStream works with binary, not text files0 As with an output file, close the input file when you are

done with it

Ch-2 Advanced Programming 91

Page 92: Chapter 2 Input Output New

Common Methodsto Test for the End of an Input File

0 A common programming situation is to read data from an input file but not know how much data the file contains

0 In these situations you need to check for the end of the file

0 There are three common ways to test for the end of a file:

1. Put a sentinel value at the end of the file and test for it.

2. Throw and catch an end-of-file exception.

3. Test for a special character that signals the end of the file (text files often have such a character).

Ch-2 Advanced Programming 92

Page 93: Chapter 2 Input Output New

The EOFException Class0 Many (but not all) methods that read from a file throw an end-of-file

exception (EOFException) when they try to read beyond the file0 all the ObjectInputStream methods in Display 9.3 do throw it

0 The end-of-file exception can be used in an "infinite" (while(true)) loop that reads and processes data from the file0 the loop terminates when an EOFException is thrown

0 The program is written to continue normally after the EOFException has been caught

Ch-2 Advanced Programming 93

Page 94: Chapter 2 Input Output New

Using EOFException

try { ObjectInputStream inputStream = new ObjectInputStream(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 e) { System.out.println("Problem with input from file numbers.dat."); }

Chapter 9 Java: an Introduction to Computer Science & Programming - Walter Savitch 94

main method fromEOFExceptionDemo

Intentional "infinite" loop to process data from input file

Note order of catch blocks:the most specific is first

and the most general last

Loop exits when end-of-file exception is thrown

Processing continues after EOFException: the input file is closed

Ch-2 Advanced Programming 94

Page 95: Chapter 2 Input Output New

Binary I/O of Class Objects0 read and write class objects in binary file

0 class must be serializable0 import java.io.*0 implement Serializable interface0 add implements Serializable to heading of class definition

0 methods used:to write object to file:writeObject method in ObjectOutputStream

to read object from file: readObject method in ObjectInputStream

public class Species implements Serializable

Ch-2 Advanced Programming 95

Page 96: Chapter 2 Input Output New

outputStream = new ObjectOutputStream( new FileOutputStream("species.records"));...Species oneRecord = new Species("Calif. Condor, 27, 0.02);...outputStream.writeObject(oneRecord);

inputStream = new ObjectInputStream( new FileInputStream("species.records"));...Species readOne = null;...readOne = (Species)inputStream.readObject(oneRecord);

readObject returns a reference to type Object so it must be cast to Species before assigning to readOne

ClassIODemo Excerpts

Ch-2 Advanced Programming 96

Page 97: Chapter 2 Input Output New

The Serializable Interface

0 Java assigns a serial number to each object written out.0 If the same object is written out more than once, after the first

write only the serial number will be written.0 When an object is read in more than once, then there will be

more than one reference to the same object.0 If a serializable class has class instance variables then they

should also be serializable.0 Why aren't all classes made serializable?

0 security issues: serial number system can make it easier for programmers to get access to object data

0 doesn't make sense in all cases, e.g., system-dependent data

Ch-2 Advanced Programming 97

Page 98: Chapter 2 Input Output New

SummaryPart 1

0 Text files contain strings of printable characters; they look intelligible to humans when opened in a text editor.

0 Binary files contain numbers or data in non-printable codes; they look unintelligible to humans when opened in a text editor.

0 Java can process both binary and text files, but binary files are more common when doing file I/O.

0 The class ObjectOutputStream is used to write output to a binary file.

Ch-2 Advanced Programming 98

Page 99: Chapter 2 Input Output New

SummaryPart 2

0 The class ObjectInputStream is used to read input from a binary file.

0 Always check for the end of the file when reading from a file. The way you check for end-of-file depends on the method you use to read from the file.

0 A file name can be read from the keyboard into a String variable and the variable used in place of a file name.

0 The class File has methods to test if a file exists and if it is read- and/or write-enabled.

0 Serializable class objects can be written to a binary file.

Ch-2 Advanced Programming 99