1 / 70

Streams and File

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.

chione
Download Presentation

Streams and File

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Streams and File

  2. 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.

  3. 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.

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

  5. 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.

  6. 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

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

  8. 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.

  9. 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

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

  11. 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.

  12. 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.

  13. 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.

  14. // 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

  15. // 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(

  16. "%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() );

  17. 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

  18. 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.

  19. 4.1. Creating a text file with the object of the Formatter class • //FileTest.java • import java.util.Formatter; • import java.io.FileNotFoundException; • import java.util.Scanner; • public class FileTest • { • public static void main(String[] args) • { • CreateFile app1= new CreateFile(); • app1.openFile(); • app1.addRecord(); • app1.closeFile(); • } • }

  20. class CreateFile • { • private Formatter output; • private Scanner input; • public void openFile() • { • try{ • output=new Formatter("client.txt"); • } • catch( FileNotFoundExceptionfileNotFoundException ) • { • System.err.println("Error in opening or craeting file"); • System.exit(1); • } • }

  21. public void addRecord() • { • input =new Scanner(System.in); • System.out.println("enter First_Name:"); • String firstName=input.next(); • System.out.println("enter Last_Name:"); • String lastName=input.next(); • System.out.println("enter Balance:"); • Double balance= input.nextDouble(); • output.format("%s %s %.2f\r\n",“Alemu",“Mamo",4605.50); • output.format("%s %s %.2f\r\n”,”Genene”,"Birhanu",3820.50); • output.format("%s %s %.2f\r\n",firstName,lastName,balance); • }

  22. public void closeFile() • { • if(output!=null) • { • output.close(); • } • } • }

  23. 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.

  24. 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.

  25. 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.

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

  27. [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.

  28. 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.

  29. 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.

  30. //FileRead.java • import java.util.Scanner; • import java.io.File; • import java.io.FileNotFoundException; • public class FileRead • { • public static void main(String[] args) • { • try • { • Scanner input =new Scanner(new File("client.txt"));

  31. while(input.hasNext()){ • String First_Name=input.next(); • String last_Name=input.next(); • double balance=input.nextDouble(); • System.out.printf("%S %s %.2f\n",First_Name,last_Name,balance); • } • } • catch(FileNotFoundException e){ • System.err.println("Error!"); • System.exit(1); • } • } • }

  32. 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.

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

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

  35. Reading in lines of characters Scanner inFile = new Scanner(new File(“in.txt")); String line; while (inFile.hasNextLine()) { line = inFile.nextLine(); // … }

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

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

  38. 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

  39. 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 [orFileWriter] • Important classes for text file input (from the file): • BufferedReader • FileReader • FileOutputStream and FileReader take file names as arguments.

  40. 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 writing PrintWriteroutputStream =new PrintWriter(new FileOutputStream("out.txt")); • Similar to the long way: FileOutputStream s = new FileOutputStream("out.txt"); PrintWriteroutputStream = new PrintWriter(s); • FileOutputStream “connects” PrintWriter to a text file.

  41. Output File Streams FileOutputStream PrintWriter Disk Memory smiley.txt out1 PrintWriterout1 = new PrintWriter( new FileOutputStream(“smiley.txt”) );

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

  43. 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:");

  44. 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("AdnewAdmasu"+sal); out1.print("DamteHabte 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(); } } }

  45. 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.

  46. 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.

  47. Lab Assignment Write a sample code for letting user tell whether to replace or append: hint 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'

  48. 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 (BufferedReaderalso 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.

  49. 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.

More Related