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.

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.
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
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.
Chapter 9 Streams and File I/O Overview of Streams and File I/O
 We can use a combination of the File and FileOutputStream to write a series of bytes to a file.
©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.
String Tokenization What is String Tokenization?
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 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 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.
Java I/O – what does it include? Command line user interface –Initial arguments to main program –System.in and System.out GUI Hardware –Disk drives ->
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.
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.
Two Ways to Store Data in a File Text format Binary format.
Chapter 10 Exceptions and File I/O. © 2004 Pearson Addison-Wesley. All rights reserved10-2 Exceptions Exception handling is an important aspect of object-oriented.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Session 05 Java Strings and Files. Exercise Complete the “quick-and-dirty” class CharacterCounter containing only a main() method that displays the number.
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.
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.
Streams and File I/O Chapter 9. Outline Overview of Streams and File I/O Text-File I/O Using the File Class Basic Binary-File I/O Object I/O with Object.
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.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
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.
Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that.
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.
OO Design and Programming II I/O: Reading and Writing
CMSC 202 Text File I/O.
Strings and File I/O.
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
Programming in Java Files and I/O Streams
CSS161: Fundamentals of Computing
Streams and File I/O Chapter 9 Chapter 9.
Streams and File I/O Chapter 14.
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
Reading and Writing Text Files
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
EEC 484/584 Computer Networks
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  I/O streams  Opening a text file for reading  Closing a stream  Reading a text file  Writing and appending to a text file

2 I/O streams  Files can be classified into two major categories: Binary files and Text files.  A binary file is a file whose contents must be handled as a sequence of binary digits.  A text file is a file whose contents are to be handled as a sequence of characters.  Why use files for I/O?  Files provide permanent storage of data.  Files provide a convenient way to deal with large quantities of data.  Recall that in In Java, I/O is handled by objects called streams.  The standard streams are System.in, System.out, and System.err.

3 Opening a text file for reading  A stream of the class BufferedReader is created and connected 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. o Example of valid filenames: “myinput.txt”, “C:\\homework\\StudentTest.java”, “C:/homework/StudentTest.java”  Both BufferedReader and FileReader classes belong to the java.io package.  The FileReader constructor throws a FileNotFoundException, if the text file to be opened for reading does not exist.  The FileNotFoundException is a subclass of the class IOException.

4 Closing a stream  When a 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 close method is defined as: public void close() throws IOException  When a stream is closed, the system releases any resources used to connect the stream to a file.  If a program does not close a stream before the program terminates, then the system will automatically close that stream.

5 Reading a text file  After a stream has been connected to a text-file for reading, the readLine or read methods of the stream can be used to read from the file:  public String readLine()throws IOException  public int read()throws IOException  The readLine method reads a line of input from the file and returns that line as a string.  If readLine attempts is to read beyond the end of file, null is returned.  The read method reads a single character from the file and returns that character as an integer value.  To obtain the character, a type cast is required: char next = (char) inputStream.read();  If read attempts is to read beyond the end of the file, -1 is returned.

6 Reading a text file: Example1  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(); }

7 Reading a text file: Example2  The following program displays the ID, number of quizzes taken, and average of each student in grades.txt: import java.io.*; import java.util.StringTokenizer; public class QuizResults{ public static void main(String[] args)throws IOException{ BufferedReader inputStream = new BufferedReader(new FileReader("grades.txt")); StringTokenizer tokenizer; String inputLine, id; int count; double sum; System.out.println("ID# Number of Quizzes Average\n"); while((inputLine = inputStream.readLine()) != null){ tokenizer = new StringTokenizer(inputLine); id = tokenizer.nextToken(); count = tokenizer.countTokens(); sum = 0.0; while(tokenizer.hasMoreTokens()) sum += Double.parseDouble(tokenizer.nextToken( )); System.out.println(id + " " + count + " ” + sum / count); }

8 Opening a text file for Writing  A stream is created and connected to a text file for writing by a statement of the form:. PrintWriter streamName = new PrintWriter(new FileWriter(filename));  Any preexisting file by the same name and in the same folder is destroyed. If the file does not exist it is created.  A stream is created and connected to a text file for appending by a statement of the form: PrintWriter streamName = new PrintWriter(new FileWriter(filename, true));  Any preexisting file by the same name is not destroyed. If the file does not exist it is created.  Both PrintWriter and FileWriter classes belong to java.io package.

9 Writing to a Text-file  The PrintWriter class has methods print and println.  The print method prints output without generating a new line.  The println method prints output, it then generates a new line.  Each constructor of the FileWriter can throw an IOException:  public FileWriter(String filename) throws IOException  public FileWriter(String filename, boolean appendFlag)throws IOException

10 Example: Appending to a Text-file import java.io.*; public class FileAppend{ public static void main(String[] args)throws IOException{ String message = "Java is platform independent"; PrintWriter outputStream = new PrintWriter(new FileWriter("datafile.txt", true)); outputStream.println(message); outputStream.close(); }  The following program appends a message to the file datafile.txt

11 Example: Writing to a Text-file  The following program copies the first 200 non-blank characters from one file to another. 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); }

12 Example: Writing to a Text-file (cont’d) try{ int count = 0; while((input = fin.read()) != -1 && count < 200){ char ch = (char) input; if(ch != ‘ ‘){ fout.print(ch); count++; } 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”); }