Sunteți pe pagina 1din 99

Topics

0 Stream 0 File I/O 0 Byte stream 0 Character Stream 0 Buffered Stream

Ch-2 Advanced Programming

Input/Output Basics
0 Input/Output = I/O = communication between a computer program and external sources and destinations of information
0 Involves Reading and Writing
0 Reading input from a source 0 Writing output to a destination

0 Example Sources and Destinations:


0 Files 0 Network connections 0 Other programs Ch-2 Advanced Programming
3

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

output stream. 0 When reading data from a stream, the stream is called an input stream. 0 If a stream has a buffer in memory, it is a buffered stream. 0 Binary Streams contain binary data. 0 Character Streams have character data and are used for storing and retrieving text
Class InputStream OutputStream Description The base class for byte stream input operations. The base class for byte stream output operations.

BufferedInputStream Buffers input from another stream in memory to make the read Ch-2 Advanced Programming 4 operations more efficient.

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

Understanding Streams(cont)

the same way: as "streams" of information 0 A stream is a sequence of data of undetermined length. There's no definite end to it. 0 In 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. 0 The key to processing the stream is a while loop that processes each piece of data, until you encounter the endof-stream character or some other exceptional condition occurs.
Ch-2 Advanced Programming 5

Input vs. Output Streams


0 Reading from an Input Stream

0 Writing to an Output Stream

Ch-2 Advanced Programming

Byte vs. Character Streams


0 All data and programs are ultimately just zeros and ones 0 each digit can have one of two values, hence binary 0 bit is one binary digit 0 byte is a group of eight bits 0 Text files: the bits represent printable characters 0 one byte per character for ASCII, the most common code 0 for example, Java source files are text files 0 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 data 0 these files are easily read by the computer but not humans 0 they are not "printable" files 0 actually, you can print them, but they will be unintelligible 0 "printable" means "easily readable by humans when printed"
Ch-2 Advanced Programming

Byte vs. Character Streams


0 Byte 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.


0 Character 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

Java Classes
0 Package java.io offers classes to connect to streams
0 To connect to a stream, instantiate a subclass of one of these abstract superclasses:

byte character

input InputStream Reader

output OutputStream Writer


9

Ch-2 Advanced Programming

Java: Text Versus Binary Files


0 Text files are more readable by humans 0 Binary files are more efficient 0 computers read and write binary files more easily than text 0 Java binary files are portable 0 they can be used by Java on different machines

0 Reading and writing binary files is normally done by a program


0 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
10

Ch-2 Advanced Programming

Text Files vs. Binary Files


0 Number: 127 (decimal) 0 Text file 0 Three bytes: 1, 2, 7 0 ASCII (decimal): 49, 50, 55 0 ASCII (octal): 61, 62, 67 0 ASCII (binary): 00110001, 00110010, 00110111 0 Binary file: 0 One byte (byte): 01111110 0 Two bytes (short): 00000000 01111110 0 Four bytes (int): 00000000 00000000 00000000

01111110

Ch-2 Advanced Programming

11

Text File I/O


0 Important classes for text file output (to the file) 0 PrintWriter 0 FileOutputStream

[or FileWriter]

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

0 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 classes 0 To use these classes your program needs a line like the following: import java.io.*;
Ch-2 Advanced Programming 12

Why Buffering?
0 Not buffered: each byte is read/written from/to disk as soon as

possible 0 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 0 Assume 16-byte buffers 0 Reading: access the first 4 bytes, need to wait for all 16 bytes are read from disk to memory 0 Writing: save the first 4 bytes, need to wait for all 16 bytes before writing from memory to disk 0 A disk operation per a buffer of bytes---lower overhead
Ch-2 Advanced Programming 13

Every File Has Two Names


1. the stream name used by Java
0 outputStream in the example

2. the name used by the operating

system
0 out.txt in the example

Ch-2 Advanced Programming

14

Text File Output


0 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 object

0 which uses FileOutputStream to open a text file


0 FileOutputStream connects PrintWriter to a text file.
Ch-2 Advanced Programming 15

Output File Streams

PrintWriter Memory

FileOutputStream Disk

outputStream

out.txt

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

Ch-2 Advanced Programming

16

Methods for PrintWriter


0 Similar to methods for System.out 0 println

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

0 print
0 format 0 flush: write buffered output to disk 0 close: close the PrintWriter stream (and file)
Ch-2 Advanced Programming 17

TextFileOutputDemo
public static void main(String[] args) { PrintWriter outputStream = null; try { Opening the file outputStream = new PrintWriter(new FileOutputStream("out.txt")); Creating a file can cause the } catch(FileNotFoundException e) FileNotFound-Exception if { the new file cannot be made. System.out.println("Error opening the file out.txt. + e.getMessage()); System.exit(0); }

Part 1

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

Ch-2 Advanced Programming

18

TextFileOutputDemo
Part 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++) { Writing to the file line = keyboard.nextLine(); outputStream.println(count + " " + line); } Closing the file outputStream.close(); System.out.println("... written to out.txt."); }

The println method is used with two different streams: outputStream Ch-2 Advanced Programmingand System.out

19

0 Writer is an abstract class to write to character streams 0 Offers write methods to write single characters, arrays of characters, and strings
void write(int c) void write(char cbuf[]) void write(String str)

Writers(Another method)

0 BufferedWriter offers efficient writing and a

newLine() method to insert a blank line

0 Close writers with close() method when done


Ch-2 Advanced Programming 20

How to Write to a Text File


public 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

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 one 0 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

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); true if user boolean append = (ans == 'A' || ans == 'a'); enters 'A' outputStream = new PrintWriter( new FileOutputStream("out.txt", append));
Ch-2 Advanced Programming 23

Closing a File
0 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

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. 0 Although 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

Text File Input


0 To open a text file for input: connect a text file to a stream for reading 0 Goal: a BufferedReader object, 0 which uses FileReader to open a text file 0 FileReader connects BufferedReader to the text file 0 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

Input File Streams

BufferedReader Memory

FileReader Disk

smileyInStream

smiley.txt

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

Ch-2 Advanced Programming

27

0 Recall: a Reader is used to read a character input stream 0 Reader offers these methods to read single characters and

Using a Reader

arrays of characters:

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

0 Reader is abstract so you must instantiate a subclass of it

to use these methods 0 The 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. 0 If 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

How to Read from a Text File


public 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

Methods for BufferedReader


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

numbers as Strings and then convert them (StringTokenizer later) 0 read: read a char at a time 0 close: close BufferedReader stream

Ch-2 Advanced Programming

30

Exception Handling with File I/O Catching IOExceptions


0 IOException is a predefined class
0 File I/O might throw an IOException 0 catch the exception in a catch block that at least prints an error message

and ends the program 0 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-notfound
Ch-2 Advanced Programming 31

Example: Reading a File Name from the Keyboard


reading a file name from the keyboard using the file name read from the keyboard reading data from the file

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(); } closing the file catch(FileNotFoundException e) { System.out.println("File " + filename + " not found."); } catch(IOException e) { System.out.println("Error reading from file " + fileName); } Ch-2 Advanced Programming 32 }
32

Chapter 10

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

0 BufferedReader has a readLine() method to

Wrap in a BufferedReader

read an entire line of characters efficiently


0 Wrap a Reader with a BufferedReader by passing the Reader as a constructor argument
FileReader fr = new FileReader("myFile.txt"); BufferedReader br = new BufferedReader(fr);

0 The readLine() method returns null when there are no more lines to read
Ch-2 Advanced Programming 33

Using BufferedReader
public 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 }

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

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 delimiters while(wordFinder.hasMoreTokens()) { System.out.println(wordFinder.nextToken()); } Question 2b Entering "Question,2b.or !tooBee." or gives this output: !tooBee
Ch-2 Advanced Programming 36

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

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 words 0 import java.util.* 0 some of its useful methods are shown in the text

0 e.g. test if there are more tokens


0 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

Delimiters
0 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 Abera Tase Gobena Biritu


Ch-2 Advanced Programming

0 Same list with a newline delimiter:

38

StringTokenizer
0 java.util.StringTokenizer separates Strings at the delimiters to extract tokens

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

delimiter characters

0 nextToken method returns the next data token between delimiters in the text 0 hasMoreTokens returns true if the text has remaining tokens
Ch-2 Advanced Programming 39

Using StringTokenizer
0 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) {} } 40 }

Putting it All Together


0 File 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 . . .

0 File 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

What We Need to Do . . .
1.

For each employee, multiply the hours worked by the hourly rate
Add this to the value of the salary to date 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.

2. 3.

Ch-2 Advanced Programming

42

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 error StringTokenizer hoursST = new StringTokenizer(hoursLine);
Ch-2 Advanced Programming 43

Opening and closing the streams to the employee

files
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) {} }
Ch-2 Advanced Programming

44

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 null 0 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 file
0 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

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


When using readLine test for null Excerpt from TextEOFDemo

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

When using read test for -1


Ch-2 Advanced Programming
Chapter 9 Java: an Introduction to Computer Science & Programming - Walter Savitch

46 46

Using Path Names


0 Path namegives name of file and tells which directory the file is

in 0 Relative path namegives the path starting with the directory that the program is in 0 Typical UNIX path name: /user/smith/home.work/java/FileClassDemo.java
0 Typical Windows path name:

D:\Work\Java\Programs\FileClassDemo.java
0 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" of which operating system it is actually running on.
Ch-2 Advanced Programming

0 Java will accept path names in UNIX or Windows format, regardless


47

File Class [java.io]


0 Acts like a wrapper class for file names 0 A file name like "numbers.txt" has only String properties 0 File has some very useful methods 0 exists: tests if a file already exists 0 canRead: tests if the OS will let you read a file 0 canWrite: tests if the OS will let you write to a file 0 delete: deletes the file, returns true if successful 0 length: returns the number of bytes in the file 0 getName: returns file name, excluding the preceding path 0 getPath: returns the path namethe full name

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


Ch-2 Advanced Programming 48

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

Alternative with Scanner


0 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

Reading in ints
Scanner inFile = new Scanner(new File(in.txt")); int number; while (inFile.hasInt()) { number = inFile.nextInt(); // }

Ch-2 Advanced Programming

51

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

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

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

BufferedReader vs Scanner (parsing primitive types)


0 Scanner 0 nextInt(), nextFloat(), for parsing types 0 BufferedReader 0 read(), readLine(), none for parsing types 0 needs StringTokenizer then wrapper class methods like Integer.parseInt(token)

Ch-2 Advanced Programming

55

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


0 BufferedReader 0 readLine() returns null 0 read() returns -1 0 Scanner 0 nextLine() throws exception 0 needs hasNextLine() to check first 0 nextInt(), hasNextInt(),

Ch-2 Advanced Programming

56

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


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

Ch-2 Advanced Programming

57

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


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

Ch-2 Advanced Programming

58

My suggestion
0 Use Scanner with File 0 new Scanner(new File(in.txt)) 0 Use hasNext() to check for EOF 0 while (inFile.hasNext()) 0 Use next() to read 0 inFile.next() 0 Simpler and you are familiar with methods for

Scanner

Ch-2 Advanced Programming

59

My suggestion cont
0 File input 0 Scanner inFile =

new Scanner(new File(in.txt));


0 File output 0 PrintWriter outFile =

new PrintWriter(new File(out.txt));


0 outFile.print(), println(), format(),

flush(), close(),

Ch-2 Advanced Programming

60

Example: Copying Text Files


void 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

Example: Scanning for a Virus


0 What is a virus? 0 software that hides itself within other executable programs 0 that executable program is the "host" for the virus 0 the virus program tries to "infect" other programs 0 the virus can cause problems that range from annoying to malicious 0 A virus that prints an annoying message stores that

string value within itself

0 we will write a program that searches through a file to

find that text, or signature

Ch-2 Advanced Programming

62

Virus-Detection Algorithm
1. Repeat the following:
a) b) c) d) read a line from a file if no line read due to EOF, terminate otherwise scan the line for specified string of text 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

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

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

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

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

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

delete the file or directory


0 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

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

List all roots


0 import java.io.File;

C:\ Free space = 30522142720 Usable space = 30522142720 Total space = 112160927744 D:\ Free space = 22253076480 Usable space = 22253076480 Total space = 254930841600 E:\ Free space = 0 Usable space = 0 Total space = 0

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

0 import java.io.RandomAccessFile;

Use RandomAccessFile to reverse a file

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

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

Use RandomAccessFile to reverse a file

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

Basic Binary File I/O


0 Important classes for binary file output (to the file) 0 ObjectOutputStream 0 FileOutputStream 0 Important classes for binary file input (from the file): 0 ObjectInputStream

0 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

Java File I/O: Stream Classes


0 ObjectInputStream and ObjectOutputStream:

0 have methods to either read or write data one byte at a time


0 automatically convert numbers and characters into binary 0 binary-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 file 0 similarly, output means data out of a program, not the file

Ch-2 Advanced Programming

76

When Using ObjectOutputStream to 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

Handling IOException
0 IOException cannot be ignored 0 either handle it with a catch block 0 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

Opening a New Output File


0

The file name is given as a String


0

file name rules are determined by your operating system

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

Example: Opening an Output File


To 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 argument 0 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

Some ObjectOutputStream Methods


0 You can write data to an output file after it is connected to a stream

class 0 Use methods defined in ObjectOutputStream 0 writeInt(int n) 0 writeDouble(double x) 0 writeBoolean(boolean b) 0 etc. 0 See the text for more

0 Note that each write method throws IOException 0 eventually we will have to write a catch block for it 0 Also note that each write method includes the modifier final 0 final methods cannot be redefined in derived classes
Ch-2 Advanced Programming 81

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

writing to it

0 Use the close method of the class

ObjectOutputStream example:

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

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

open

Ch-2 Advanced Programming

82

Writing a Character to a File: an Unexpected Little Complexity 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

Writing a boolean Value to a File


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

false
0 true 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

Writing Strings to a File: Another Little Unexpected Complexity


0 Use the writeUTF method to output a value of type String 0 there is no writeString method 0 UTF stands for Unicode Text Format 0 a special version of Unicode 0 Unicode: a text (printable) code that uses 2 bytes per character 0 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 characters 0 allows other languages without sacrificing efficiency for ASCII files
Ch-2 Advanced Programming

85

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

Opening a New Input File


0 Similar to opening an output file, but replace "output" with "input" 0 The file name is given as a String 0 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 code
Ch-2 Advanced Programming 87

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 argument 0 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

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

class 0 Use methods defined in ObjectInputStream 0 readInt() 0 readDouble() 0 readBoolean() 0 etc. 0 See the text for more

0 Note that each write method throws IOException


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

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 IOException 0 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

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 types

the correct read method 0 ObjectInputStream works with binary, not text files
0 As with an output file, close the input file when you are

0 it is up to the programmer to know their order and use

done with it

Ch-2 Advanced Programming

91

Common Methods to 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

The EOFException Class


0 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 0 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 file 0 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

Using EOFException
main method from EOFExceptionDemo Intentional "infinite" loop to process data from input file Loop exits when end-offile exception is thrown Processing continues after EOFException: the input file is closed Note order of catch blocks: the most specific is first and the most general last
Chapter 9

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."); } Ch-2 Advanced Programming 94

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

94

Binary I/O of Class Objects


0 read and write class objects in binary file 0 class must be serializable 0 import java.io.* 0 implement Serializable interface

0 add implements Serializable to heading of class definition

public class Species implements Serializable


0 methods used:

to write object to file: writeObject method in ObjectOutputStream

to read object from file: readObject method in ObjectInputStream


95

Ch-2 Advanced Programming

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

ClassIODemo Excerpts
inputStream = new ObjectInputStream( new FileInputStream("species.records")); ... readObject returns a reference to Species readOne = null; type Object so it must be cast to Species before assigning to readOne ... readOne = (Species)inputStream.readObject(oneRecord);
Ch-2 Advanced Programming 96

The Serializable Interface


0 Java assigns a serial number to each object written out.

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

0 If the same object is written out more than once, after the first

97

Summary
Part 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

Summary
0 The class ObjectInputStream is used to read input from

Part 2

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

S-ar putea să vă placă și