Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Chapter 11 – Files and Streams 1 Introduction What are files? –Long-term storage of large amounts of data –Persistent data exists after termination of.

Similar presentations


Presentation on theme: "1 Chapter 11 – Files and Streams 1 Introduction What are files? –Long-term storage of large amounts of data –Persistent data exists after termination of."— Presentation transcript:

1 1 Chapter 11 – Files and Streams 1 Introduction What are files? –Long-term storage of large amounts of data –Persistent data exists after termination of program –Files stored on secondary storage devices Magnetic disks Optical disks Magnetic tapes Class File –Provides useful information about a file or directory –Does NOT open files, create files or process files

2 2 File Objects To operate on a file, we must first create a File object (from the package java.io). –Creates a file object that associates the file sample.dat in the current directory. File inFile = new File("sample.dat"); –Creates a file object that associates the file test.dat in the directory C:\SamplePrograms File inFile = new File ("C:/SamplePrograms/test.dat");

3 3 Some File Methods File provides a set of methods to examine files/directories. - boolean exists() Tests whether the file or directory exists. - boolean isFile() Tests whether the file is a normal file. - boolean canWrite() Tests whether the application can modify to the file. - boolean isDirectory() Tests whether the file is a directory. - long length() Returns the length of the file, 0 for directory. - String[] list() Returns an array of strings naming the files and subdirectories in the directory. - String getName() Returns the name of the file or directory.

4 4 Example 1 import java.io.*; public class FileTest { public static void main( String args[] ) { if (args.length != 1) { System.out.println("Usage : FileTest "); System.exit(0); } File f = new File(args[0]); System.out.println("f.exists() = " + f.exists()); System.out.println("f.isFile() = " + f.isFile()); System.out.println("f.isDirectory() = " + f.isDirectory()); System.out.println("f.length() = " + f.length()); if (f.isDirectory()) { String sub[] = f.list(); System.out.println("Content of this directory:"); for (int i=0; i<sub.length; i++) System.out.println(" " + sub[i]); } >java FileTest FileTEst.java f.exists() = true f.isFile() = true f.isDirectory() = false f.length() = 649 >java FileTest temp f.exists() = true f.isFile() = false f.isDirectory() = true f.length() = 0 Content of this directory: FileTest.java CapName.java StaticCharMethods.htm

5 5 FileWriter Java views a file as a stream of bytes –File ends with end-of-file marker or a specific byte number –File as a stream of bytes associated with an object Class FileWriter is used for output of character data to a disk file. The example program constructs a FileWriter stream. This also creates a disk file in the current directory, named " hello.txt ". The write () method is called several times to write characters to the disk file. Then the file is closed.

6 6 FileWriter import java.io.*; class WriteTextFile { public static void main ( String[] args ) throws IOException { String fileName = "hello.txt" ; FileWriter OutFile = new FileWriter( fileName ); OutFile.write( "Java Programming is interesting\n" ); OutFile.write( "and challenging. Java file is very useful\n" ); OutFile.write( "and easy to operate.\n" ); OutFile.close(); }

7 7 Sample Run >dir 06/04/00 07:55p. 06/04/00 07:55p.. 06/04/00 07:55p 693 WriteTextFile.class 06/04/00 07:55p 475 WriteTextFile.java >java WriteTextFile >dir 06/04/00 07:56p. 06/04/00 07:56p.. 06/04/00 07:56p 120 hello.txt 06/04/00 07:55p 693 WriteTextFile.class 06/04/00 07:55p 475 WriteTextFile.java >type hello.txt Java Programming is interesting and challenging. Java file IO is very useful and easy to operate. Content of "hello.txt"

8 8 FileWriter Constructors The two constructors that interest us are: FileWriter(String fileName) FileWriter(String fileName, boolean append) If append is true, the second constructor will open an existing file for writing without destroying its contents. If the file does not exist, it will be created.

9 9 IO Exception Most IO methods throw an IOException when an error is encountered. A method that uses one of these IO methods MUST either (1) say throws IOException in its header, or (2) perform its IO in a try-catch block and catch exceptions. The program on next page is the example program modified to catch exceptions. The constructor, the write() method, and the close() method can throw an IOException. All are caught by the catch block. This program opens the file "hello.txt" for appending. Run it twice and see what it does.

10 10 IO Exception import java.io.*; class AppendTextFile { public static void main ( String[] args ) { String fileName = "hello.txt" ; try { // append characters to the file FileWriter outFile = new FileWriter( fileName, true ); outFile.write( "Java Programming is interesting\n" ); outFile.write( "and challenging. Java file is very useful\n" ); outFile.write( "and easy to operate.\n" ); outFile.close(); } catch ( IOException iox ) { System.out.println("Problem writing " + fileName ); }

11 11 Disk input and output is more efficient when a buffer is used. Programs that do extensive IO should use buffers. The BufferedWriter stream is used for this with a character output stream. –BufferedWriter(Writer out) Construct a buffered character-output stream Since FileWriter is a Writer, it is the correct type for the parameter. The BufferedWriter Stream BufferedWriter out = new BufferedWriter(new FileWriter("a.txt"));

12 12 import java.io.*; class BufferedTextFile { public static void main ( String[] args ) { String fileName = "hello.txt" ; try { BufferedWriter outFile = new BufferedWriter( new FileWriter(fileName) ); outFile.write( "Java Programming is interesting\n" ); outFile.write( "and challenging. Java file is very\n" ); outFile.write( "useful and easy to manage.\n" ); outFile.close(); } catch ( IOException iox ) { System.out.println("Problem writing " + fileName ); } Updated Example

13 13 To read text from text files we can use FileReader and BufferedReader. –BufferedReader in = new BufferedReader( new FileReader(fileName) ); The readLine() method reads a line of characters from a BufferedReader. File Input

14 14 BufferedReader Example import java.io.*; class ReadTextFile { public static void main ( String[] args ) { String fileName = "hello.txt" ; String line; try { BufferedReader in = new BufferedReader(new FileReader(fileName)); line = in.readLine(); while ( line != null ) { // continue until end of file System.out.println( line ); line = in.readLine(); } in.close(); } catch ( IOException iox ) { System.out.println("Problem reading " + fileName ); } Sample Run >java ReadTextFile Java Programming is interesting and challenging. Java file is very useful and easy to operate.

15 15 Text File Copy Program The following program copies a source text file to a destination text file. An already existing file with the same name as destination file will be destroyed. import java.io.*; public class CopyTextFile { public static void main ( String[] args ) { // to avoid using static methods CopyMaker cm = new CopyMaker(); cm.copy("source.txt", "target.txt"); } source.txt Hello John. I am....... target.txt Hello John. I am....... java CopyTextFile

16 16 Text File Copy Program class CopyMaker { String sourceName, destName; BufferedReader source; BufferedWriter dest; String line; public boolean copy(String src, String dst ) { sourceName = src ; destName = dst ; return openFiles() && copyFiles() && closeFiles(); } return immediately if any of these methods returns false

17 17 Text File Copy Program private boolean openFiles() // return true if files open, else false { // open the source try { source = new BufferedReader(new FileReader( sourceName )); } catch ( IOException iox ) { System.out.println("Problem opening " + sourceName ); return false; } // open the destination try { dest = new BufferedWriter(new FileWriter( destName )); } catch ( IOException iox ) { System.out.println("Problem opening " + destName ); return false; } return true; }

18 18 Text File Copy Program private boolean copyFiles() // return true if copy worked,else false { try { line = source.readLine(); while ( line != null ) { dest.write(line); // write the string dest.newLine(); // write a '\n', same as dest.write("\n"); line = source.readLine(); } catch ( IOException iox ) { System.out.println("Problem reading or writing" ); return false; } return true; }

19 19 Text File Copy Program private boolean closeFiles() //return true if files close,else false { boolean retVal=true; // close the source try { source.close(); } catch ( IOException iox ) { System.out.println("Problem closing " + sourceName ); retVal = false; } // close the destination try { dest.close(); } catch ( IOException iox ) { System.out.println("Problem closing " + destName ); retVal = false; } return retVal; } } // end class CopyMaker

20 20 Example - Simple Report Generation 1 Programming in Java 223 8 3 Core Java 1 173 5 4 Core Java 2 173 3 7 Java Tutorial 220 9 Write a program to read transaction records from a text file and generate a report. 1 Programming in Java 223 8 1784 3 Core Java 1 173 5 865 4 Core Java 2 173 3 519 7 Java Tutorial 220 9 1980 Input File (salesinfo.txt) Output File (report.txt) First Record 1st line : item no 2nd line : book name 3rd line : price and quantity Second Record repeat.......

21 21 Example - Simple Report Generation import java.io.*; import java.util.*; import javax.swing.*; public class GenReport { public static void main ( String[] args ) { ReportMaker rm = new ReportMaker(); if (args.length!=2) { System.out.println("Usage: GenReport "); System.exit(-1); } if (rm.process(args[0], args[1])) { System.out.println("Report generation completed."); } else { System.out.println("Report generation failed."); } System.exit(0); }

22 22 Example - Simple Report Generation class ReportMaker { String sourceName, destName; BufferedReader source; BufferedWriter dest; String line; private boolean openFiles() // SAME AS CopyTextFile....... public boolean process(String src, String dst) { sourceName = src ; destName = dst ; return openFiles() && genReport() && closeFiles(); } private boolean closeFiles() // SAME AS CopyTextFile.......

23 23 Example - Simple Report Generation private boolean genReport() { int itemID, price, quantity; String name; String spaces = " "; try { line = source.readLine(); while ( line != null ) { itemID = Integer.parseInt(line); name = source.readLine(); // make "name" 20 characters long name = name + spaces.substring(0, (20 - name.length()) - 1); line = source.readLine(); StringTokenizer st = new StringTokenizer(line); price = Integer.parseInt(st.nextToken()); quantity = Integer.parseInt(st.nextToken());

24 24 Example - Simple Report Generation dest.write(itemID + " " + name + " " + price + " " + quantity + " " + (price*quantity) ); dest.newLine(); line = source.readLine(); } catch ( IOException iox ) { System.out.println("Problem reading or writing" ); return false; } return true; }


Download ppt "1 Chapter 11 – Files and Streams 1 Introduction What are files? –Long-term storage of large amounts of data –Persistent data exists after termination of."

Similar presentations


Ads by Google