1 Chapter 15 – Files I/O basics File I/O Classes File I/O Basic Operations Text File Output PrintWriter import Statement with a * Text File Input Scanner,

Slides:



Advertisements
Similar presentations
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. 2 Operating System Application #1 Application #2 Java Virtual Machine #1 Local Memory Shared Memory Threads.
Advertisements

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.
1 Streams and Input/Output Files Part 3. 2 Handling Primitive Data Types The basic input and output streams provide read/write methods that can be used.
Lecture 15: I/O and Parsing
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
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.
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.
 We can use a combination of the File and FileOutputStream to write a series of bytes to a file.
Chapter 10 File I/O Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
CS102--Object Oriented Programming Lecture 13: File I/O Copyright © 2008 Xiaoyan Li.
Lecture 7 File I/O (and a little bit about exceptions)‏
Unit 211 File IO Binary Files Reading and Writing Binary Files Writing Objects to files Reading Objects from files.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L07 (Chapter 18) Binary I/O.
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 prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Chapter 10 File I/O Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 91 Streams and File I/O Chapter 9. 2 Reminders Project 6 released: due Nov 10:30 pm Project 4 regrades due by midnight tonight Discussion.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L08 (Chapter 18) Binary I/O.
Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Java File I/O (Continued). File I/O in Java Like every other programming language, Java supports the writing to and reading from different files with.
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.
Files and Streams. Java I/O File I/O I/O streams provide data input/output solutions to the programs. A stream can represent many different kinds of sources.
Input / Output Chapter 13.  We use files all the time  Programs are files  Documents are files  We want them to be “permanent”  To last beyond execution.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Chapter 15 – Files I/O basics File I/O Classes File I/O Basic Operations Text File Output PrintWriter import Statement with a * Text File Input Scanner,
Files and Streams. Midterm exam Time: Wednesday, October 31, 2007 Format: Multiple choices (about 15 to 20 questions) Determine the results of the code.
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.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
JAVA I/O © EnhanceEdu, IIIT Hyderabad. Contents 3/29/2010EnhanceEdu, IIIT - H 2  Command Line I/O  File Class  Streams  Byte Streams [Low level and.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Chapter 9-Text File I/O. Overview n Text File I/O and Streams n Writing to a file. n Reading from a file. n Parsing and tokenizing. n Random Access n.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
Introduction to Computation and Problem Solving Class 29: Introduction to Streams Prof. Steven R. Lerman and Dr. V. Judson Harward.
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.
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.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
 Pearson Education, Inc. All rights reserved Files and Streams.
1 Chapter 19 Binary I/O. 2 Motivations F Data stored in a text file – is represented in human-readable form –Text file –Readable –Java source programs.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 12 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/ George Koutsogiannakis 1.
File Input and Output Appendix E © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Chapter 10 File I/O Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Simple Java I/O Part I General Principles. Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
Up to slide 46 for 111. Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
1 Text File Input and Output. Objectives You will be able to Write text files from your Java programs. Read text files in your Java programs. 2.
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
Streams & File Input/Output (I/O)
CMSC 202 Text File I/O.
Object Writing in files
I/O Basics.
Chapter 17 Binary I/O 1.
Chapter 10 File I/O Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Chapter 10 File I/O Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Streams and File I/O Chapter 9 Chapter 9.
CSS 161: Fundamentals of Computing
MSIS 670: Object-Oriented Software Engineering
OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS
Chapter 10 File I/O Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage Copyright © 2016 Pearson Inc.
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
David Davenport Spring 2005
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 Chapter 15 – Files I/O basics File I/O Classes File I/O Basic Operations Text File Output PrintWriter import Statement with a * Text File Input Scanner, FileReader HTML File Generator Text Format Versus Binary Format Binary I/O Output with: DataOutputStream, FileOutputStream Input with: DataInputStream, FileInputStream Object I/O Output with: ObjectOutputStream, FileOutputStream Input with: ObjectInputStream, FileInputStream 1

2 I/O Basics So far, all input has come from the keyboard and all output has been to the console window. Keyboard and console input/output (I/O) is temporary, not permanent. For permanent I/O, use files. Benefit of reading input from a file: Allows input to be reused without having to re-enter the input via the keyboard. Benefits of saving output to a file: Allows output to be re-viewed without having to rerun the program. Allows program chaining where the output of one program is used as the input for another program. 1 2

3 File I/O Classes For programs that manipulate files, you'll need to use several pre- built classes from the Java API library. The Java API is organized as a hierarchy of packages where each package contains a group of classes. Here's the file I/O portion of the Java API library:

4 File I/O Classes There are lots of classes that deal with file I/O, and there's overlap with some of those classes. In other words, some classes handle the same sort of file operation(s). The book covers the file I/O classes that are the easiest to use. Here are the file I/O classes that the book covers: If you want to write text to a file, use the PrintWriter class. If you want to read text from a file, use the Scanner and FileReader classes. If you want to write objects to a file, use the ObjectOutputStream and FileOutputStream classes. If you want to read objects from a file, use the ObjectInputStream and FileInputStream classes. When you write "text" to a file, you store the text as characters where each character is represented by its ASCII value. When you write an object to a file, you store the object's instance variables in their native bytecode format, not as ASCII characters.

5 File I/O Basic Operations There are four basic steps when performing file I/O: Import the appropriate classes. For input and output, import the java.io package. For input, also import the java.util.Scanner class. Open the file by instantiating the appropriate class(es). Write to or read from the file by calling the appropriate method. With output files, only write operations are allowed (not read operations). With input files, only read operations are allowed (not write operations). Close the file by calling the close method. 1

6 Text File Output To open a text file for output: Instantiate the PrintWriter class like this: PrintWriter ; = new PrintWriter( ); The PrintWriter constructor throws a FileNotFoundException. To handle the exception, surround the constructor call in a try block, and add a FileNotFoundException catch block. To write to the opened text file: Call the instantiated PrintWriter object's print and println methods. They're the same methods that handle output to a console window. To close the opened text file: Call the instantiated PrintWriter object's close method like this:.close();

7 Text File Output import java.util.Scanner; import java.io.*; public class WriteTextFile { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); PrintWriter fileOut; String text = "Hello, world!"; try { System.out.print("Enter filename: "); fileOut = new PrintWriter(stdIn.nextLine()); fileOut.println(text); fileOut.close(); } catch (FileNotFoundException e) { System.out.println("Error: " + e.getMessage()); } } // end main } // end WriteTextFile class open the file for the PrintWriter constructor call write to the file close the file

8 Import Statement with a * In the WriteTextFile program, note this import statement: import java.io.*; That statement is necessary so that the program's PrintWriter and FileNotFoundException classes get imported ( PrintWriter and FileNotFoundException are in the java.io package). The * is a "wildcard." It represents all classes within the specified package. Using an * with the import statement causes all the classes in the specified package to be imported. Benefit of using an * with the import statement: It leads to less code (particularly if you need to import more than one class from the same package). Benefit of specifying the class name as part of the import statement: The code is self documenting (it's obvious which class you want to import). 2 1

9 Text File Output By default, when opening a file with PrintWriter, the file's contents are deleted. Consequently, the file's first print statement causes output to be placed at the beginning of the empty file. If you don't want to delete file's original contents: 1. You can open a file in append mode by embedding a FileWriter object in a PrintWriter constructor call. That causes the file's print statements to insert text at the end of the file. Syntax: PrintWriter ; = new PrintWriter( new FileWriter(, true)); or … 2nd argument specifies append mode on/off 2 1 3

10 Text File Output If you don't want to delete file's original contents: 2. You can open a file as a random access file with the RandomAccessFile class. Random access allows a program to move freely within a file, writing and reading at specified positions. Syntax: RandomAccessFile ; = new RandomAccessFile(, "rw")); "rw" specifies read/write mode 1 2 3

11 Text File Input To open a text file for input: Instantiate the Scanner and FileReader classes like this: Scanner ; = new Scanner(new FileReader( )); The FileReader constructor throws a FileNotFoundException. To handle the exception, surround the constructor call in a try block, and add a FileNotFoundException catch block. To read from the opened text file: Call the instantiated Scanner object's "next" methods. They're the same methods that handle keyboard input with the Scanner class - nextLine, nextInt, nextDouble, etc. To close the opened text file: Call the instantiated Scanner object's close method like this:.close();

12 Text File Input import java.util.Scanner; import java.io.*; public class ReadTextFile { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); Scanner fileIn; try { System.out.print("Enter filename: "); fileIn = new Scanner(new FileReader(stdIn.nextLine())); while (fileIn.hasNextLine()) { System.out.println(fileIn.nextLine()); } fileIn.close(); } catch (FileNotFoundException e) { System.out.println("Error: " + e.getMessage()); } } // end main } // end ReadTextFile class open the file for the FileReader constructor call read a line from the file and print it close the file 1 2 3

13 Text File Input When you read from a Scanner object (using nextLine, nextInt, etc.), you read sequentially. That means your first read operation reads from the beginning of the file and subsequent read operations read from subsequent portions of the file. If you read through the entire file and then attempt to read past the end of the file, your program will crash (more specifically, it will throw a NoSuchElementException ). To prevent reading past the end of the file, call the Scanner class's hasNextLine method prior to reading from the file. The hasNextLine method returns true if it's safe to read from the file (i.e., it returns true if the file "has a next line"). The hasNextLine method returns false otherwise. Note this code fragment from the ReadTextFile program: while (fileIn.hasNextLine()) { System.out.println(fileIn.nextLine()); }

14 HTML File Generator The upcoming program copies the contents of a user-specified file and pastes it into a newly generated HTML file. Sample File (family.txt) Our Family We have a dog, Barkley. Barkley is a good dog. She sleeps a lot and digs up the grass. We feed her twice a day. We have two kids, Jordan and Caiden. They're girls. They like to eat, cry, and play. We like them a lot. Generated HTML File (family.html) Our Family Our Family We have a dog, Barkley. Barkley is a good dog. She sleeps a lot and digs up the grass. We feed her twice a day. We have two kids, Jordan and Caiden. They're girls. They like to eat, cry, and play. We like them a lot

15 HTML File Generator import java.util.Scanner; import java.io.*; public class HTMLGenerator { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); String filenameIn; // original file's name Scanner fileIn; // input file int dotIndex; // position of dot within filename String filenameOut; // HTML file's name PrintWriter fileOut; // HTML file String line; // a line from the input file System.out.print("Enter file's name: "); filenameIn = stdIn.nextLine(); 1

16 HTML File Generator try { fileIn = new Scanner(new FileReader(filenameIn)); dotIndex = filenameIn.lastIndexOf("."); if (dotIndex == -1) // no dot found { filenameOut = filenameIn + ".html"; } else // dot found { filenameOut = filenameIn.substring(0, dotIndex) + ".html"; } fileOut = new PrintWriter(filenameOut); // First line is used for title and header elements. line = fileIn.nextLine(); if (line == null) { System.out.println(filenameIn + " is empty."); }

17 HTML File Generator else { // Write starting HTML code. fileOut.println(" "); fileOut.println(" " + line + " "); fileOut.println(" "); fileOut.println(" " + line + " "); while (fileIn.hasNextLine()) { line = fileIn.nextLine(); // Blank lines generate p tags. if (line.isEmpty()) { fileOut.println(" "); } // end if 1 2 3

18 HTML File Generator else { fileOut.println(line); } } // end while // Write ending HTML code. fileOut.println(" "); } // end else fileIn.close(); fileOut.close(); } // end try catch (IOException e) { System.out.println("Error: " + e.getMessage()); } // end catch } // end main } // end class HTMLGenerator 1 2 3

19 Text Format Versus Binary Format Java can handle two types of file formats – text file format and binary file format. Text file format: Text file data is stored using 8-bit ASCII values. Since the ASCII character set is a universal standard, text files can be viewed using standard text editors and they can be read by programs written in any language (not just Java). To facilitate reading and writing data one line at a time, text file data is organized using newline characters. When printing to a text file, Java uses a println method to specify that a newline is to be inserted at the end of the line. Likewise, when reading from a file, Java uses a nextLine method to specify that an entire line of characters is to be read in. 1 2

20 Text Format Versus Binary Format Example data: Bob 2222 Paul5555 How it's stored in a UNIX-created text file: Text files created in a UNIX environment use only one character, \n, to represent a new line. Text files created in a Windows environment use two characters, \r (carriage return) and \n (newline), to represent a new line, but Windows also reads UNIX-created lines. Bob2222\nP aul5555\n

21 Text Format Versus Binary Format (hidden) Example data: Bob 2222 Paul5555 How it's stored in a UNIX-created text file: Text files created in a UNIX environment use only one character, \n, to represent a new line. Text files created in a Windows environment use two characters, \r (carriage return) and \n (newline), to represent a new line, but Windows also reads UNIX- created lines. Bob2222\nP aul5555\n

22 Text Format Versus Binary Format Binary file format: When writing values to a binary file, Java's native storage schemes are used. Binary files do not facilitate writing and reading data one line at a time. Specifically, binary files do not use println and readline methods to print an entire line or read an entire line, respectively. Instead, binary files use writeChar, readChar, writeInt, readInt, writeDouble, readDouble, etc. methods to write and read individual primitive-type variables

23 Text Format Versus Binary Format Example data: Bob How it's stored in a binary file: Bob

24 Text Format Versus Binary Format Benefits of text format: Easy to view the file (because all standard text editors can display ASCII values). Text files can be read by programs written in any language (not just Java). Benefits of binary format: Text format can only handle ASCII values, but binary format can handle all of the Unicode characters. Using binary format can lead to programs that run faster because when a program writes to or reads from a binary file, the data doesn't have to be converted. On the other hand, when a program writes to or reads from a text file, the data has to converted between Java native format and ASCII format. 1 2

25 Binary File Output To open a binary file for primitive data output, instantiate a FileOutputStream object. To transform primitive data types into bytes, instantiate a DataOutputStream object. Example: DataOutputStream fileOut;... fileOut = new DataOutputStream( new FileOutputStream(filename, true));... open file

26 Binary File Output Output Example: Write a doubleValues array to previously opened binary file with DataOutputStream ’s writeDouble method, like this: Other DataOutputStream methods: void writeInt(int i) void writeChar(int ch) void writeChars(String s) for (int i=0; i<doubleValues.length; i++) { fileOut.writeDouble(doubleValues[i]); } 1 2

27 Binary File Input To open a binary file for primitive data input, instantiate a FileInputStream object. To transform primitive data types into bytes, instantiate a DataInputStream object. Example: DataInputStream fileIn;... fileIn = new DataInputStream( new FileInputStream(filename)); open file

28 Binary File Input Input Example: Fill a doubleData array with data from previously opened binary file with DataInputStream ’s readDouble method, like this: for (int i=0; i<doubleData.length; i++) { doubleData[i] = fileIn.readDouble(); } Other DataInputStream methods: int readInt() char readChar() 1 2

29 Object File I/O Problem: In OOP, most data is in object format, and the structure of objects is user-specified. So there is no universal format for storing objects in files, and each object’s variables must be stored separately using a format that is appropriate for that type of object. This makes writing or reading an object’s data to or from a file very tedious. Solution: Automate this process with Java’s “serialization” service. To get this service, append the following to the heading of any class you want to use this service: implements Serializable The JVM handles all the details

30 Object File I/O Output: fileOut = new ObjectOutputStream( new FileOutputStream(filename)); fileOut.writeObject(testObject); fileOut.close(); Input: fileIn = new ObjectInputStream( new FileInputStream(filename)); testObject = (TestObject) fileIn.readObject(); fileIn.close(); open file

31 Chapter 15 - Quiz Questions 3.In the book, what does the example Web page describe? a)a family b)a pet shop c)a travel agency 2)Which of the following is not one of the basic steps in file I/O? a)Open the file by instantiating the appropriate class(es). b)Cast the file to an int. c)Write to or read from the file by calling the appropriate method. d)Close the file by calling the close method. 1.You can create or view binary or object files with most text editors. (T / F)