70
Streams and File

Streams and File

  • Upload
    chione

  • View
    52

  • Download
    0

Embed Size (px)

DESCRIPTION

Streams and File. 1. Introduction. Data stored in variables and arrays is temporary For long-term retention of data, even after the programs that create the data terminate, computers use files. Data maintained in files is persistent data—it exists beyond the duration of program execution. - PowerPoint PPT Presentation

Citation preview

Page 1: Streams and File

Streams and File

Page 2: Streams and File

1. Introduction• Data stored in variables and arrays is temporary• For long-term retention of data, even after the

programs that create the data terminate, computers use files.

• Data maintained in files is persistent data—it exists beyond the duration of program execution.

• In this chapter, we explain how Java programs create, update and process files.

Page 3: Streams and File

2. Files and Streams

• Java views each file as a sequential stream of bytes. Every operating system provides a mechanism to determine the end of a file, such as an end-of-file marker.

• A Java program processing a stream of bytes simply receives an indication from the operating system when it reaches the end of the stream—the program does not need to know how the underlying platform represents files or streams.

Page 4: Streams and File

Byte-Based and Character-Based Streams

• File streams can be used to input and output data as bytes or characters.

• Byte-based streams input and output data in its binary format.• Character-based streams input and output data as a sequence

of characters.• If the value 5 were being stored using a byte-based stream, it

would be stored in the binary format of the numeric value 5, or 101.

• If the value 5 were being stored using a character-based stream, it would be stored in the binary format of the character 5, or 00000000 00110101 (this is the binary representation for the numeric value 53, which indicates the Unicode® character 5).

Page 5: Streams and File

• The difference between the two forms is that the numeric value can be used as an integer in calculations, whereas the character 5 is simply a character that can be used in a string of text

• Files that are created using byte-based streams are referred to as binary files, while files created using character-based streams are referred to as text files.

• Text files can be read by text editors, while binary files are read by programs that understand the file’s specific content and its ordering.

Page 6: Streams and File

Standard Input, Standard Output and Standard Error Streams

• A Java program opens a file by creating an object and associating a stream of bytes or characters with it.

• Java can also associate streams with different devices. When a Java program begins executing, in fact, it creates three stream objects that are associated with devices—System.in, System.out and System.err.

• System.in (the standard input stream object) normally enables a program to input bytes from the keyboard

Page 7: Streams and File

• object System.out (the standard output stream object) normally enables a program to output character data to the screen

• Object System.err (the standard error stream object) normally enables a program to output character-based error messages to the screen.

• Each stream can be redirected. For System. in, this capability enables the program to read bytes from a different source. For System. out and System.err, it enables the output to be sent to a different location, such as a file on disk.

• Class System provides methods setIn, setOut and setErr to redirect the standard input, output and error streams, respectively.

Page 8: Streams and File

The java.io Package

• Java programs perform file processing by using classes from package java.io.

• This package includes definitions for stream classes, such as FileInputStream (for byte-based input from a file), FileOutputStream (for byte-based output to a file), FileReader (for character- based input from a file) and FileWriter (for character-based output to a file), which inherit from classes InputStream, OutputStream, Reader and Writer, respectively.

Page 9: Streams and File

• Java contains classes that enable you to perform input and output of objects or variables of primitive data types. The data will still be stored as bytes or characters behind the scenes, allowing you to read or write data in the form of ints, Strings, or other types without having to worry about the details of converting such values to byte format. To perform such input and output, objects of classes ObjectInputStream and ObjectOutput- Stream can be used together with the byte-based file stream classes FileInputStream and FileOutputStream

Page 10: Streams and File

• Java offers many classes for performing input/output operations.

• In addition to the java.io classes, character-based input and output can be performed with classes Scanner and Formatter. Class Scanner is used extensively to input data from the keyboard—it can also read data from a file. Class Formatter enables formatted data to be output to any text-based stream in a manner similar to method System.out.printf.

Page 11: Streams and File

3. Class File

• class File, which is useful for retrieving information about files or directories from disk. Objects of class File do not open files or provide any file-processing capabilities. However, File objects are used frequently with objects of other java.io classes

• Class File provides four constructors. The one with a String argument specifies the name of a file or directory to associate with the File object. The name can contain path information as well as a file or directory name.

Page 12: Streams and File

• The constructor with two String arguments specifies an absolute or relative path as the first argument and the file or directory to associate with the File object as the second argument.

• The constructor with File and String arguments uses an existing File object that specifies the parent directory of the file or directory specified by the String argument.

• The fourth constructor uses a URI object to locate the file. A Uniform Resource Identifier (URI) is a more general form of the Uniform Resource Locators (URLs) that are used to locate websites.

Page 13: Streams and File

• For example, http://www.deitel.com/ is the URL for the Deitel & Associates website. URIs for locating files vary across operating systems. On Windows platforms, the URI file://C:/data.txt identifies the file data.txt stored in the root directory of the C

• Figure 17.2 lists some common File methods.

Page 14: Streams and File
Page 15: Streams and File

// Fig. 17.3: FileDemonstration.java// File class used to obtain file and directory information.import java.io.File;import java.util.Scanner;

public class FileDemonstration{ public static void main( String[] args ) { Scanner input = new Scanner( System.in );

System.out.print( "Enter file or directory name: " ); analyzePath( input.nextLine() ); } // end main

Page 16: Streams and File

// display information about file user specifies public static void analyzePath( String path ) { // create File object based on user input File name = new File( path );

if ( name.exists() ) // if name exists, output information about it

{ // display file (or directory) information System.out.printf(

Page 17: Streams and File

"%s%s\n%s\n%s\n%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s",

name.getName(), " exists", ( name.isFile() ? "is a file" : "is not a file" ), ( name.isDirectory() ? "is a directory" : "is not a directory" ), ( name.isAbsolute() ? "is absolute path" : "is not absolute path" ), "Last modified: ", name.lastModified(), "Length: ", name.length(), "Path: ", name.getPath(), "Absolute path: ", name.getAbsolutePath(), "Parent: ", name.getParent()

);

Page 18: Streams and File

if ( name.isDirectory() ) // output directory listing { String[] directory = name.list(); System.out.println( "\n\nDirectory contents:\n" ); for ( String directoryName : directory ) System.out.println( directoryName ); } // end if } // end outer if else // not file or directory, output error message { System.out.printf( "%s %s", path, "does not exist." ); } // end else } // end method analyzePath} // end class FileDemonstration

Page 19: Streams and File

4.Sequential-Access Text Files• We begin with text files, enabling the reader to

quickly create and edit human-readable files. We discuss creating, writing data to, reading data from and updating sequential-access text files.

Creating a Sequential-Access Text File

• Java imposes no structure on a file—notions such as records do not exist as part of the Java language. Therefore, you must structure files to meet the requirements of your applications.

Page 20: Streams and File

4.1. Creating a text file with the object of the Formatter class1. //FileTest.java2. import java.util.Formatter;3. import java.io.FileNotFoundException;4. import java.util.Scanner;5. public class FileTest6. {7. public static void main(String[] args)8. {9. CreateFile app1= new CreateFile();10. app1.openFile();11. app1.addRecord();12. app1.closeFile();13. }14. }

Page 21: Streams and File

15. class CreateFile16. {17. private Formatter output;18. private Scanner input;19. public void openFile()20. {21. try{22. output=new Formatter("client.txt");23. }24. catch( FileNotFoundException fileNotFoundException )25. {26. System.err.println("Error in opening or craeting file");27. System.exit(1);28. }29. }

Page 22: Streams and File

30. public void addRecord()31. {32. input =new Scanner(System.in);33. System.out.println("enter First_Name:");34. String firstName=input.next();35. System.out.println("enter Last_Name:");36. String lastName=input.next();37. System.out.println("enter Balance:");38. Double balance= input.nextDouble();39. output.format("%s %s %.2f\r\n",“Alemu",“Mamo",4605.50);40. output.format("%s %s %.2f\r\n”,”Genene”,"Birhanu",3820.50);41. output.format("%s %s %.2f\r\

n",firstName,lastName,balance);42. }

Page 23: Streams and File

43.public void closeFile()44.{45.if(output!=null)46.{47.output.close();48.}49.}50.}

Page 24: Streams and File

• output is a Formatter variable• a Formatter object outputs formatted Strings,

using the same formatting capabilities as method System.out.printf.

• A Formatter object can output to various locations, such as the screen or a file

• The constructor used in line 22 takes one argument—a String containing the name of the file, including its path. If a path is not specified, as is the case here, the JVM assumes that the file is in the directory from which the program was executed.

Page 25: Streams and File

• If the file does not exist, it will be created. If an existing file is opened, its contents are truncated—all the data in the file is discarded.

• At this point(Line 22) the file is open for writing, and the resulting Formatter object can be used to write data to the file.

• Lines 24–28 handle the FileNotFoundException, which occurs if the file does not exist and a new file cannot be created. This exception may also occur if there’s an error opening the file.

Page 26: Streams and File

• we call static method System.exit and pass the value 1. This method terminates the application. An argument of 0 to method exit indicates successful program termination. A nonzero value, such as 1 in this example, normally indicates that an error has occurred. This value is passed to the command window that executed the program. The argument is useful if the program is executed from a batch file on Windows systems or a shell script on UNIX/ Linux/Mac OS X systems.

• Batch files and shell scripts offer a convenient way of executing several programs in sequence. When the first program ends, the next program begins execution. It’s possible to use the argument to method exit in a batch file or shell script to determine whether other programs should execute.

Page 27: Streams and File

• The record’s information is written to clients.txt (lines 39-40) using method format, which can perform identical formatting to the System.out.printf

• Method format outputs a formatted String to the output destination of the Formatter object—the file clients.txt.

• The format string "%s %s %.2f\n" indicates that the current record will be stored as a String (the first name), another String (the last name) and a floating-point value (the balance). Each piece of information is separated from the next by a space, and the double value (the balance) is output with two digits to the right of the decimal point (as indicated by the .2 in %.2f).

Page 28: Streams and File

• [Note: You can also output data to a text file using class java.io.PrintWriter, which provides format and printf methods for outputting formatted data.]

• Line 47 closes the object by simply calling method close. If method close is not called explicitly, the operating system normally will close the file when program execution terminates—this is an example of operating-system “housekeeping.” However, you should always explicitly close a file when it’s no longer needed.

Page 29: Streams and File

Platform-Specific Line-Separator Characters• different platforms use different line-separator

characters. On UNIX/ Linux/Mac OS X, the line separator is a newline (\n). On Windows, it’s a combination of a carriage return and a line feed—represented as \r\n.

• The method System.out.println outputs a platform-specific line separator after its argument. Also, regardless of the line separator used in a text file, a Java program can still recognize the lines of text and read them.

Page 30: Streams and File

4.2. Reading Data from a Sequential-Access Text File

• This section shows how to read data sequentially from a text file and we demonstrate how class Scanner can be used to input data from a file rather than the keyboard.

Page 31: Streams and File

1. //FileRead.java2. import java.util.Scanner;3. import java.io.File;4. import java.io.FileNotFoundException;5. public class FileRead6. {7. public static void main(String[] args)8. {9. try10. {11.Scanner input =new Scanner(new File("client.txt"));

Page 32: Streams and File

12. while(input.hasNext()){13. String First_Name=input.next();14. String last_Name=input.next();15. double balance=input.nextDouble();16. System.out.printf("%S %s %.2f\

n",First_Name,last_Name,balance);17. }18. }19. catch(FileNotFoundException e){20. System.err.println("Error!");21. System.exit(1);22. }23. }24. }

Page 33: Streams and File

• The file is opened for reading by instantiating a Scanner object in line 11.

• We pass a File object to the constructor, which specifies that the Scanner object will read from the file "clients.txt" located in the directory from which the application executes. If the file cannot be found, a FileNotFoundException occurs. The exception is handled in lines 19–22.

Page 34: Streams and File

• Lines 12–17 read data from the file until the end-of-file marker is reached (in which case, method hasNext will return false at line 12).

• If no exceptions occur, the record’s information is displayed on the screen

• Each iteration of the loop inputs one line of text from the text file, which represents one record.

• define method closeFile, which closes the Scanner (recommended).

Page 35: Streams and File

Reading in int’s

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

number = inFile.nextInt(); // …

}

Page 36: Streams and File

Reading in lines of charactersScanner inFile = new Scanner(new File(“in.txt"));String line;while (inFile.hasNextLine()) {

line = inFile.nextLine(); // …

}

Page 37: Streams and File

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

Page 38: Streams and File

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

Page 39: Streams and File

Streams• Stream: an object that either delivers data to its

destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.)– it acts as a buffer between the data source and

destination• Input stream: a stream that provides input to a program

– System.in is an input stream• Output stream: a stream that accepts output from a

program– System.out is an output stream

• A stream connects a program to an I/O object– System.out connects a program to the screen– System.in connects a program to the keyboard

Page 40: Streams and File

6 .Additional java.io Classes• This section overviews additional interfaces and classes

(from package java.io) for character-based input and output streams.

• Important classes for text file output (to the file)– PrintWriter– FileOutputStream [or FileWriter]

• Important classes for text file input (from the file):– BufferedReader– FileReader

• FileOutputStream and FileReader take file names as arguments.

Page 41: Streams and File

• To use these classes your program needs a line like the following:import java.io.*;

Text File Output• To open a text file for output: connect a text file to a stream

for writingPrintWriter outputStream =

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

• Similar to the long way:FileOutputStream s = new FileOutputStream("out.txt");PrintWriter outputStream = new PrintWriter(s);• FileOutputStream “connects” PrintWriter to a text file.

Page 42: Streams and File

Output File Streams

PrintWriter FileOutputStream

DiskMemory

out1 smiley.txt

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

Page 43: Streams and File

import java.io.PrintWriter;import java.io.FileOutputStream;import java.io.FileNotFoundException;import java.util.Scanner;public class WriteFile5{public static void main(String[] args){WriteFile6 file1=new WriteFile6();file1.openFile();file1.addRecord();file1.close();}}

Page 44: Streams and File

class WriteFile6{private PrintWriter out1;public void openFile(){try{out1=new PrintWriter(new FileOutputStream("Comp1.txt"));}catch(FileNotFoundException e){System.err.println("ERorr!");}}

public void addRecord(){Scanner inp1=new Scanner(System.in);System.out.println("Enter first name:");String fn=inp1.nextLine();System.out.println("Enter Last name:");

Page 45: Streams and File

String ln=inp1.nextLine();System.out.println("Enter Salary:");double sal=inp1.nextDouble();out1.format("%s %s %.2f\r\n","Abebe","Getachew",2786.56);out1.println("Adnew Admasu"+sal);out1.print("Damte Habte 675.89\r\n");out1.format("%s %s %.2f\r\n","Kebede","Belachew",345.78);out1.format("%s %s %.2f",fn,ln,sal);

}public void close(){if(out1!=null){out1.close();}}}

Page 46: Streams and File

Overwriting a File• Opening an output file creates an empty file

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

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

• To see how to check for existence of a file, see the section of the text that discusses the File class.

Page 47: Streams and File

Java Tip: Appending to a Text File

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

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

• Second parameter: append to the end of the file if it exists.

Page 48: Streams and File

• Lab AssignmentWrite a 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();boolean append = (ans == 'A' || ans == 'a');outputStream = new PrintWriter(

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

true if user enters 'A'

hint

Page 49: Streams and File

Closing a File

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

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

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

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

are open.

Page 50: Streams and File

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.

Page 51: Streams and File

Text File Input• To open a text file for input: connect a text file to a stream for

reading• a BufferedReader object, which uses FileReader to open a

text file– FileReader “connects” BufferedReader to the text file

• For example:BufferedReader smileyInStream = new BufferedReader(new FileReader(“smiley.txt"));

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

Page 52: Streams and File

Input File Streams

BufferedReader FileReader

DiskMemory

inp1 smiley.txt

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

Page 53: Streams and File

import java.io.BufferedReader;import java.io.FileReader;import java.io.FileNotFoundException;import java.io.IOException;import java.util.StringTokenizer;//import java.io.File;public class ReadFile4 {public static void main(String[] args){try{BufferedReader inp1=new BufferedReader(new FileReader("Computer

Sc.txt"));String emp=inp1.readLine();

Page 54: Streams and File

while(emp!=null){System.out.println(emp);emp=inp1.readLine();}}

Page 55: Streams and File

catch(FileNotFoundException e){System.err.println("Error!");System.exit(1);}catch(IOException e){System.err.println("Error from reading file!");}}}

Page 56: Streams and File

Methods for BufferedReader

• readLine: read a line into a String• read: read a char at a time• close: close BufferedReader stream• no methods to read numbers directly, so read

numbers as Strings and then convert them (StringTokenizer later)

Page 57: Streams and File

Reading Words in a StringUsing StringTokenizer Class

• 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– import java.util.*– you can specify delimiters (the character or characters that

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

and newline)

Page 58: Streams and File

import java.io.BufferedReader;import java.io.FileReader;import java.io.FileNotFoundException;import java.io.IOException;import java.util.StringTokenizer;//import java.io.File;public class ReadFile4 {public static void main(String[] args){try{BufferedReader inp1=new BufferedReader(new FileReader("Computer

Sc.txt"));String emp=inp1.readLine();

Page 59: Streams and File

while(emp!=null){StringTokenizer wordFinder = new StringTokenizer(emp," ");while(wordFinder.hasMoreTokens()){ System.out.println(wordFinder.nextToken());}

//System.out.println(emp);emp=inp1.readLine();}}

Page 60: Streams and File

catch(FileNotFoundException e){System.err.println("Error!");System.exit(1);}catch(IOException e){System.err.println("Error from reading file!");}}}

Page 61: Streams and File

Example: StringTokenizer• 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:

Page 62: Streams and File

Testing for End of File in a Text File

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

a text file

• read returns -1 when it tries to read beyond the end of a text file

Page 63: Streams and File

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 63

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

When using readLinetest for null

When using read test for -1

Page 64: Streams and File

BufferedReader vs Scanner(parsing primitive types)

• Scanner– nextInt(), nextFloat(), … for parsing

types• BufferedReader

– read(), readLine(), … none for parsing types

– needs StringTokenizer then wrapper class methods like Integer.parseInt(token)

Page 65: Streams and File

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

• BufferedReader– readLine() returns null– read() returns -1

• Scanner– nextLine() throws exception– needs hasNextLine() to check first– nextInt(), hasNextInt(), …

Page 66: Streams and File

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

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

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

Page 67: Streams and File

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

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

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

Page 68: Streams and File

My suggestion

• Use Scanner with File– new Scanner(new File(“in.txt”))

• Use hasNext…() to check for EOF– while (inFile.hasNext…())

• Use next…() to read– inFile.next…()

• Simpler and you are familiar with methods for Scanner

Page 69: Streams and File

My suggestion cont…

• File input– Scanner inFile = new Scanner(new File(“in.txt”));

• File output– PrintWriter outFile = new PrintWriter(new File(“out.txt”));– outFile.print(), println(), format(), close(), …

Page 70: Streams and File

7. Reading Assignment- Opening Files with JFileChooser

• Class JFileChooser displays a dialog (known as the JFileChooser dialog) that enables the user to easily select files or directories.