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.

Slides:



Advertisements
Similar presentations
1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
Advertisements

Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Lecture 15: I/O and Parsing
Files from Ch4. File Input and Output  Reentering data all the time could get tedious for the user.  The data can be saved to a file. Files can be input.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12 File Input and Output.
File Handling and Serialization CSIS 3701: Advanced Object Oriented Programming.
Files Files are used to store long term data. –Typically referred to as persistent data. –A file is a group of related records. –A list of friends addresses.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 12 File Input and Output.
James Tam Exception handling in Java Java Exception Handling Dealing with errors using Java’s exception handling mechanism.
James Tam Simple file handling in Java Simple File Input And Output Types of Java files Simple file output in Java Simple file input in Java.
Tim Wentz Nathaniel Smith Andrew Johnson. Files in Java Create a new file handle using: ▫new File(String pathname); Pathnames can be either relative or.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
Files and Streams CS 21a Chapter 11 of Horstmann.
1 CS2200 Software Development Lecture 36: File Processing A. O’Riordan, 2008 (Includes slides by Lewis/Loftus 2205 and K. Brown )
1 Text File I/O  I/O streams  Opening a text file for reading  Closing a stream  Reading a text file  Writing and appending to a text file.
James Tam Simple File Input And Output Types of Java Files Simple File Output in Java Simple File Input in Java.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
Two Ways to Store Data in a File Text format Binary format.
Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class.
CIS 260: App Dev I. 2 Objects and Reference Variables n Predefined Java classes you have used:  String —for defining and manipulating strings  Integer.
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer.
Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Text Input and Output on the Console.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Program data (instance variables, local variables, and parameters) is transient, because its lifetime ends with the program...if not, before. Sometimes.
Based on OOP with Java, by David J. Barnes Input-Output1 The java.io Package 4 Text files Reader and Writer classes 4 Byte stream files InputStream, FileInputStream,
OOP with Java, David J. Barnes Input-Output1 A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated.
SE-1020 Dr. Mark L. Hornick 1 File Input and Output.
Programs & Data Files Notes Data information processed by word processing, spreadsheet or other application programs are stored as data files. Java programs,
I/O in Java Dennis Burford
Files. Advantages of files Can edit data, prepare ahead of time Can rerun file without reentering data Can examine output at leisure Can display output.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
By Rachel Thompson and Michael Deck.  Java.io- a package for input and output  File I/O  Reads data into and out of the console  Writes and reads.
Chapter 15 Text Processing and File Input/Output Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin,
CS101 Lab “File input/Output”. File input, output File : binary file, text file READ/WRITE class of “text file” - File Reading class : FileReader, BufferedReader.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Files and Streams CS /02/05 L7: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
Lecture 5 I/O and Parsing
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
Chapter 9 1 Chapter 9 – Part 2 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
1 Exceptions Exception handling – Exception Indication of problem during execution – E.g., divide by zero – Chained exceptions Uses of exception handling.
Chapter - 11 Introduction to File and Streams This chapter includes -  Defining a File  Testing and Checking File Objects  Accessing File Objects.
Files and console applications Chapter 17 This chapter explains: What a file is How to read and write to files How to manipulate folder paths and file.
Programs & Data Files Notes Data information processed by word processing, spreadsheet or other application programs are stored as data files. Java.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Georgia Institute of Technology Making Text for the Web part 2 Barb Ericson Georgia Institute of Technology March 2006.
CS 116 Object Oriented Programming II Lecture 11 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
1 Input-Output A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated as transparently as.
OO Design and Programming II I/O: Reading and Writing
Lecture 5 Text File I/O; Parsing.
Lesson 8: More File I/O February 5, 2008
Introduction to programming in java
Strings and File I/O.
CHAPTER 5 JAVA FILE INPUT/OUTPUT
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
File class File myFile=new File(“c:/javaDemo/aa
Streams and File I/O Chapter 14.
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
Reading and Writing Text Files
18 File i/o, Parsing.
EEC 484/584 Computer Networks
Presentation transcript:

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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 Example - Simple Report Generation 1 Programming in Java Core Java Core Java Java Tutorial Write a program to read transaction records from a text file and generate a report. 1 Programming in Java Core Java Core Java Java Tutorial 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 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 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 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 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; }