Starting Out with Java: From Control Structures Through Objects Sixth Edition

Similar documents
Chapter 11: Exceptions and Advanced File I/O

Chapter 12: Exceptions and Advanced File I/O

Chapter 4: Loops and Files

Chapter 4: Loops and Files

Object-Oriented Programming in Java

Chapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved.

Streams and File I/O

Streams and File I/O

Data Structures. 03 Streams & File I/O

Dec. 16/ Deciding Which Loop to Use

14.3 Handling files as binary files

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Chapter 17 Binary I/O. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved.

Lecture 7. File Processing

HST 952. Computing for Biomedical Scientists Lecture 8

Active Learning: Streams

CS 251 Intermediate Programming Java I/O Streams

CS112 Lecture: Streams

CSB541 Network Programming 網路程式設計. Ch.2 Streams 吳俊興國立高雄大學資訊工程學系

5/29/2006. Announcements. Last Time. Today. Text File I/O Sample Programs. The File Class. Without using FileReader. Reviewed method overloading.

File I/O Array Basics For-each loop

Performing input and output operations using a Byte Stream

Introduction Unit 4: Input, output and exceptions

1.00 Lecture 30. Sending information to a Java program

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O

CPS122 Lecture: Input-Output

Streams and File I/O

When working with files and directories, it is often

Basic I/O - Stream. Java.io (stream based IO) Java.nio(Buffer and channel-based IO)

File IO. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 20

Simple Java Input/Output

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Agenda & Reading. Python Vs Java. COMPSCI 230 S Software Construction

Exceptions Binary files Sequential/Random access Serializing objects

CISC 323 (Week 9) Design of a Weather Program & Java File I/O

C17: I/O Streams and File I/O

CPS122 Lecture: Input-Output

Fundamental Java Syntax Summary Sheet for CISC101, Spring Java is Case - Sensitive!

PIC 20A Streams and I/O

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Programming Languages and Techniques (CIS120)

Input, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003

09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.

Input-Output and Exception Handling

Chapter 4 Java I/O. X i a n g Z h a n g j a v a c o s q q. c o m

Overview CSE 143. Input and Output. Streams. Other Possible Kinds of Stream Converters. Stream after Stream... CSE143 Wi

Java Input/Output. 11 April 2013 OSU CSE 1

Unit 10: exception handling and file I/O

Experiment No: Group B_4

Lecture 22. Java Input/Output (I/O) Streams. Dr. Martin O Connor CA166

File Input and Output Review CSC 123 Fall 2018 Howard Rosenthal

Project 1. Java Data types and input/output 1/17/2014. Primitive data types (2) Primitive data types in Java

CSC 1214: Object-Oriented Programming

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Sp

Files and Streams

File I/O Introduction to File I/O Text Files The File Class Binary Files 614

CSC Java Programming, Fall Java Data Types and Control Constructs

File Processing. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. A Class for Representing a File

File. Long term storage of large amounts of data Persistent data exists after termination of program Files stored on secondary storage devices

A variable is a name for a location in memory A variable must be declared

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP 202 File Access 1

We now start exploring some key elements of the Java programming language and ways of performing I/O

Exceptions and Working with Files

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Au

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Chapter 12. File Input and Output. CS180-Recitation

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Text User Interfaces. Keyboard IO plus

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003

CS Programming I: File Input / Output

Lecture 19 Programming Exceptions CSE11 Fall 2013

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Objec&ves. Review. Standard Error Streams

When we reach the line "z = x / y" the program crashes with the message:

Computational Expression

7 Streams and files. Overview. Binary data vs text. Binary data vs text. Readers, writers, byte streams. input-output

Programming Languages and Techniques (CIS120)

File Input/Output. Introduction to Computer Science I. Overview (1): Overview (2): CSE 1020 Summer Bill Kapralos. Bill Kapralos.

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. File Input and Output

Java Programming Lecture 9

Tirgul 1. Course Guidelines. Packages. Special requests. Inner classes. Inner classes - Example & Syntax

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

Dining philosophers (cont)

Full file at

CS Programming I: File Input / Output

Full file at

Object-Oriented Programming in the Java language

Training topic: OCPJP (Oracle certified professional Java programmer) or SCJP (Sun certified Java programmer) Content and Objectives

Textbook. Topic 8: Files and Exceptions. Files. Types of Files

I/O Streams. Object-oriented programming

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Using Java Classes Fall 2018 Margaret Reid-Miller

Optional Lecture Chapter 17 Binary IO

Programming Languages and Techniques (CIS120)

Transcription:

Starting Out with Java: From Control Structures Through Objects Sixth Edition Chapter 11 I/O

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 files or output files. Files: Files have to be opened. Data is then written to the file. The file must be closed prior to program termination. In general, there are two types of files: binary text

Writing Text to a File To open a file for text output you create an instance of the PrintWriter class.

The PrintWriter Class (1 of 3) The PrintWriter class allows you to write data to a file using the print and println methods, as you have been using to display data on the screen. Just as with the System.out object, the println method of the PrintWriter class will place a newline character after the written data. The print method writes data without writing the newline character.

The PrintWriter Class (2 of 3)

The PrintWriter Class (3 of 3) To use the PrintWriter class, put the following import statement at the top of the source file: See example: FileWriteDemo.java

Exceptions (1 of 3) When something unexpected happens in a Java program, an exception is thrown. The method that is executing when the exception is thrown must either handle the exception or pass it up the line. Handling the exception will be discussed later. To pass it up the line, the method needs a throws clause in the method header.

Exceptions (2 of 3) To insert a throws clause in a method header, simply add the word throws and the name of the expected exception. PrintWriter objects can throw an IOException, so we write the throws clause like this:

Appending Text to a File To avoid erasing a file that already exists, create a FileWriter object in this manner: Then, create a PrintWriter object in this manner:

Specifying a File Location (1 of 2) On a Windows computer, paths contain backslash (\) characters. Remember, if the backslash is used in a string literal, it is the escape character so you must use two of them:

Specifying a File Location (2 of 2) This is only necessary if the backslash is in a string literal. If the backslash is in a String object then it will be handled properly. Fortunately, Java allows Unix style filenames using the forward slash (/) to separate directories:

Reading Data From a File (1 of 3) You use the File class and the Scanner class to read data from a file:

Reading Data From a File (2 of 3) The lines above: Creates an instance of the Scanner class to read from the keyboard Prompt the user for a filename Get the filename from the user Create an instance of the File class to represent the file Create an instance of the Scanner class that reads from the file

Reading Data From a File (3 of 3) Once an instance of Scanner is created, data can be read using the same methods that you have used to read keyboard input (nextline, nextint, nextdouble, etc).

Exceptions (3 of 3) The Scanner class can throw an IOException when a File object is passed to its constructor. So, we put a throws IOException clause in the header of the method that instantiates the Scanner class. See Example: ReadFirstLine.java

Detecting the End of a File (1 of 2) The Scanner class s hasnext() method will return true if another item can be read from the file.

Detecting the End of a File (2 of 2) See example: FileReadDemo.java

Binary Files (1 of 6) The way data is stored in memory is sometimes called the raw binary format. Data can be stored in a file in its raw binary format. A file that contains binary data is often called a binary file. Storing data in its binary format is more efficient than storing it as text. There are some types of data that should only be stored in its raw binary format.

Binary Files (2 of 6) Binary files cannot be opened in a text editor such as Notepad. To write data to a binary file you must create objects from the following classes: FileOutputStream - allows you to open a file for writing binary data. It provides only basic functionality for writing bytes to the file. DataOutputStream - allows you to write data of any primitive type or String objects to a binary file. Cannot directly access a file. It is used in conjunction with a FileOutputStream object that has a connection to a file.

Binary Files (3 of 6) A DataOutputStream object is wrapped around a FileOutputStream object to write data to a binary file. If the file that you are opening with the FileOutputStream object already exists, it will be erased and an empty file by the same name will be created.

Binary Files (4 of 6) These statements can combined into one. Once the DataOutputStream object has been created, you can use it to write binary data to the file. Example: WriteBinaryFile.java

Binary Files (5 of 6) To open a binary file for input, you wrap a DataInputStream object around a FileInputStream object. These two statements can be combined into one

Binary Files (6 of 6) The FileInputStream constructor will throw a FileNotFoundException if the file named by the string argument cannot be found. Once the DataInputStream object has been created, you can use it to read binary data from the file. Example: ReadBinaryFile.java

Writing and Reading Strings (1 of 2) To write a string to a binary file, use the DataOutputStream class s writeutf method. This method writes its String argument in a format known as UTF 8 encoding. Just before writing the string, this method writes a twobyte integer indicating the number of bytes that the string occupies. Then, it writes the string s characters in Unicode. (UTF stands for Unicode Text Format.) The DataInputStream class s readutf method reads from the file.

Writing and Reading Strings (2 of 2) To write a string to a file: To read a string from a file: The readutf method will correctly read a string only when the string was written with the writeutf method. Example: Write UTF.java Read UTF.java

Appending Data to Binary Files The FileOutputStream constructor takes an optional second argument which must be a boolean value. If the argument is true, the file will not be erased if it exists; new data will be written to the end of the file. If the argument is false, the file will be erased if it already exists.

Random Access Files (1 of 5) Text files and the binary files previously shown use sequential file access. With sequential access: The first time data is read from the file, the data will be read from its beginning. As the reading continues, the file s read position advances sequentially through the file s contents. Sequential file access is useful in many circumstances. If the file is very large, locating data buried deep inside it can take a long time.

Random Access Files (2 of 5) Java allows a program to perform random file access. In random file access, a program may immediately jump to any location in the file. To create and work with random access files in Java, you use the RandomAccessFile class. filename: the name of the file. mode: a string indicating the mode in which you wish to use the file. r = reading rw = for reading and writing.

Random Access Files (3 of 5) When opening a file in r mode where the file does not exist, a FileNotFoundException will be thrown. Opening a file in r mode and trying to write to it will throw an IOException. If you open an existing file in rw mode, it will not be deleted and the file s existing content will be preserved.

Random Access Files (4 of 5) Items in a sequential access file are accessed one after the other. Items in a random access file are accessed in any order. If you open a file in rw mode and the file does not exist, it will be created. A file that is opened or created with the RandomAccessFile class is treated as a binary file.

Random Access Files (5 of 5) The RandomAccessFile class has: the same methods as the DataOutputStream class for writing data, and the same methods as the DataInputStream class for reading data. The RandomAccessFile class can be used to sequentially process a binary file. Example: WriteLetters.java

The File Pointer (1 of 5) The RandomAccessFile class treats a file as a stream of bytes. The bytes are numbered: the first byte is byte 0. The last byte s number is one less than the number of bytes in the file. These byte numbers are similar to an array s subscripts, and are used to identify locations in the file. Internally, the RandomAccessFile class keeps a long integer value known as the file pointer.

The File Pointer (2 of 5) The file pointer holds the byte number of a location in the file. When a file is first opened, the file pointer is set to 0. When an item is read from the file, it is read from the byte that the file pointer points to. Reading also causes the file pointer to advance to the byte just beyond the item that was read. If another item is immediately read, the reading will begin at that point in the file.

The File Pointer (3 of 5) An EOFException is thrown when a read causes the file pointer to go beyond the size of the file. Writing also takes place at the location pointed to by the file pointer. If the file pointer points to the end of the file, data will be written to the end of the file. If the file pointer holds the number of a byte within the file, at a location where data is already stored, a write will overwrite the data at that point.

The File Pointer (4 of 5) The RandomAccessFile class lets you move the file pointer. This allows data to be read and written at any byte location in the file. The seek method is used to move the file pointer. The argument is the number of the byte that you want to move the file pointer to.

The File Pointer (5 of 5) Example: ReadRandomLetters.java