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.

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

Lecture 15: I/O and Parsing
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
Chapter 10 Ch 1 – Introduction to Computers and Java Streams and File IO 1.
10-1 Writing to a Text File When a text file is opened in this way, a FileNotFoundException can be thrown – In this context it actually means that the.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
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.
1 Fall 2009ACS-1903 The break And continue Statements a break statement can be used to abnormally terminate a loop. use of the break statement in loops.
Chapter 9 Streams and File I/O Overview of Streams and File I/O
©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.
1 LECTURE#7: Console Input Overview l Introduction to Wrapper classes. l Introduction to Exceptions (Java run-time errors). l Console input using the BufferedReader.
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.
1 StringTokenizer and StringBuffer classes Overview l StringTokenizer class l Some StringTokenizer methods l StringTokenizer examples l StringBuffer class.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
1 File Input. 2 Reading Files We have already seen that writing files is (can be?) similar to using System.out Not surprisingly, reading from files is.
1 Introduction to Console Input  Primitive Type Wrapper Classes  Converting Strings to Numbers  System.in Stream  Wrapping System.in in a Buffered.
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.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
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.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
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.
Introduction To Scientific Programming Chapter 9 – Stream & File I/O.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Two Ways to Store Data in a File Text format Binary format.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
1 Java Console I/O Introduction. 2 Java I/O You may have noticed that all the I/O that we have done has been output The reasons –Java I/O is based on.
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.
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,
I/O in Java Dennis Burford
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
File IO Basics By Dan Fleck Coming up: Data Streams.
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,
1 StringTokenization Overview l StringTokenizer class l Some StringTokenizer methods l StringTokenizer examples.
CS101 Lab “File input/Output”. File input, output File : binary file, text file READ/WRITE class of “text file” - File Reading class : FileReader, BufferedReader.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Lecture 5 I/O and Parsing
Chapter 10 Text Files Section 10.2 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
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.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
I/O Basics Java does provide strong, flexible support for I/O related to files and networks. Java’s console based interaction is limited since in real.
File Input and Output Appendix E © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
CSI 3125, Preliminaries, page 1 Files. CSI 3125, Preliminaries, page 2 Reading and Writing Files Java provides a number of classes and methods that allow.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Announcements/Reminders l Project 6 due on Thursday March 31 (3 weeks)
Java I/O 1. Java I/O (Input and Output) is used to process the input and produce the output based on the input. The java.io package contains all the classes.
For Friday Finish reading chapter 9 WebCT quiz 17.
OO Design and Programming II I/O: Reading and Writing
CMSC 202 Text File I/O.
Streams and File I/O.
Strings and File I/O.
I/O Basics.
Streams and File I/O Chapter 9 Chapter 9.
Streams and File I/O Chapter 14.
Reading and Writing Text Files
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
ECE 122 April 14, 2005.
Java Chapter 2 (Estifanos Tilahun Mihret--Tech with Estif)
Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program, then the stream.
Presentation transcript:

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 Writing or appending to a text file l Preview: StringTokenizer and StringBuffer classes.

2 I/O streams Binary and Text files l Binary file: A file whose contents must be handled as a sequence of binary digits. l Text file: A file whose contents are to be handled as a sequence of characters. Why use files for I/O? 1. Files provide permanent storage of data. 2. Files provide a convenient way to deal with large quantities of data. I/O streams l In Java, I/O is handled by streams. l An input stream is an object that takes data from a source and delivers it to a program. l An output stream is an object that takes data from a program and delivers data it to a destination. l Java has the following standard streams: System.in, System.out, and System.err. System.in is connected to the keyboard. System.out and System.err are connected to the screen.

3 Opening a text file for reading You create a stream of the class BufferedReader and connect it to a text file for reading as follows: BufferedReader streamName = new BufferedReader (new FileReader(filename)); Where filename is a File object or a constant string or a String variable containing the name or the full path of the file to be read. Example of valid filenames: 1. “myinput.txt” 2. “C:\\homework\\StudentTest.java” 3. “C:/homework/StudentTest.java” 4. fileObject = new File(“C:/homework/StudentTest.java”); BufferedReader streamName = new BufferedReader (new FileReader(fileObject));    The full path to a file can be read from the keyboard; in that case you must not type any of the backslashes twice.

4 Opening a text file for reading (Cont’d) l The class BufferedReader has no constructor that takes a file name or a File object as its argument. l The class FileReader will accept a file name (or an object of the class File) as a constructor argument and produce a stream that is a Reader. l The constructor for BufferedReader will accept a Reader as an argument. l Both BufferedReader and FileReader classes belong to the java.io package. l The FileReader constructor throws a FileNotFoundException, if the text file to be opened for reading does not exist: FileReader(String filename) throws FileNotFoundException l The FileNotFoundException is a subclass of the class IOException, so any catch-block that catches exceptions of the class IOException will also catch exceptions of the class FileNotFoundException.

5 Reading a text file After a text file has been opened for reading you can use the methods readLine( ) or read( ) of the stream to read from the file: 1. public String readLine( ) throws IOException This method reads a line of input from the input stream and returns that line as a string. If an attempt is made to read beyond the end of file, null is returned. 2.public int read( ) throws IOException This method reads a single character from the input stream and returns that character as an integer value. To obtain the character, you must perform a type cast on the value returned. For example: char next = (char) inputStream.read( ) If an attempt is made to read beyond the end of the file, -1 is returned. Note: The end of file may be detected by using the boolean method ready( ) of an input stream. The method returns false if the end of file is reached; otherwise it returns true:... String input = inputStream.readLine( ); while( inputStream.ready( ) ) {... input = inputStream.readLine( ); }

6 Closing a stream When your program has finished writing to or reading from a file, it should close the stream connected to that file by calling the close( ) method of the stream: streamName.close( ) The method close( ) is defined as: public void close( ) throws IOException »When you close a file, the system releases any resources used to connect the stream to the file. »If your program does not close a file before the program ends, then the system will close it for you.

7 Example1 (File display) l Example: The following program displays the contents of the file myinput.txt on the screen by reading one character at a time: import java.io.*; public class ShowFile { public static void main(String[ ] args) throws IOException { int input; BufferedReader fin = null; try { fin = new BufferedReader(new FileReader("myinput.txt")); } catch(FileNotFoundException e) { System.out.println("Error - File myinput.txt not found"); System.exit(1); } while( ( input = fin.read( )) != -1) System.out.print((char) input); fin.close( ); }

8 Reading numbers from a text file l The BufferedReader class has no methods that can read a number. l To read a number from a text file, use the parse method of an appropriate Wrapper class. l Example: The following program reads float numbers from a file. It displays the numbers on the screen, computes their average, and displays that average on the screen: import java.io.*; public class Average { public static void main(String[ ] args) { try{ BufferedReader fin = new BufferedReader(new FileReader("numbers.txt")); String inputLine; float grade, sum = 0.0F; int count = 0; while( ( inputLine = fin.readLine( )) != null) { grade = Float.parseFloat(inputLine); sum += grade; count++; System.out.println(grade); }

9 Reading numbers from a text file (Cont’d) if(count = = 0) System.err.println("Error - no grades were read"); else System.out.println("\nThe average is " + sum / count); fin.close( ); } catch(FileNotFoundException e) { System.err.println("Error - File myinput.txt not found"); } catch(IOException e) { System.err.println("Error - An I/O error occured"); } catch(NumberFormatException e) { System.err.println("Error - An invalid float number read"); }

10 Writing or appending to a text file A text file is opened for writing, either one character at a time or one line at a time, by a statement of the form: PrintWriter streamName = new PrintWriter(new FileWriter(filename)); Any preexisting file by the same name is destroyed. A text file is opened for appending, either one character at a time or one line at a time, by a statement of the form: PrintWriter streamName = new PrintWriter(new FileWriter(filename, true)); Any preexisting file by the same name is not destroyed. Both PrintWriter and FileWriter classes belong to java.io package.  The PrintWriter class has methods print( ) and println( ) that print either one character or one line at a time. Each constructor of the FileWriter can throw an IOException: FileWriter(String filename) throws IOException FileWriter(String filename, boolean appendFlag) throws IOException

11 Writing or appending to a text file (Cont’d) The class FileWriter has constructors that takes a filename or a File object as its argument; however this class does not have methods to write one line at a time. The class PrintWriter does not have a constructor that takes a filename or an object of the class File as its argument; however it has a constructor that takes a FileWriter object as argument. It also has a method to write one line at a time.  So we use the class FileWriter together with the class PrintWriter.

12 Example (Copying a text file) Example: The following program copies one file to another; but it converts every lowercase character to uppercase. import java.io.*; public class FileCopy{ public static void main(String[ ] args) { int input; BufferedReader fin = null; PrintWriter fout = null; try { fin = new BufferedReader(new FileReader("myinput.txt")); } catch(FileNotFoundException e){ System.out.println("Input File not found"); System.exit(1); } try{ fout = new PrintWriter(new FileWriter("myoutfile.txt")); } catch(IOException e){ System.out.println("Error opening output file"); System.exit(1); }

13 Example (Copying a text file) (Cont’d) try { while(( input = fin.read( )) != -1 ) { char ch = (char) input; if(Character.isLowerCase(ch)) ch = Character.toUpperCase(ch); fout.print(ch); } catch(IOException e) { System.out.println("Error in reading the file myinput.txt"); } try{ fin.close( ); fout.close( ); } catch(IOException e) { System.out.println("Error in closing a file"); } System.out.println("File copied successfully"); }