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

Similar documents
Streams and File I/O

HST 952. Computing for Biomedical Scientists Lecture 8

CSPP : Introduction to Object-Oriented Programming

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

1.00 Lecture 30. Sending information to a Java program

Simple Java Input/Output

Darshan Institute of Engineering & Technology for Diploma Studies

Data Structures. 03 Streams & File I/O

IT101. File Input and Output

Streams and File I/O

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

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

CSC 1214: Object-Oriented Programming

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

CS 251 Intermediate Programming Java I/O Streams

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

Object-Oriented Programming Design. Topic : Streams and Files

Java Input/Output. 11 April 2013 OSU CSE 1

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

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

COMP Streams and File I/O. Yi Hong June 10, 2015

Exceptions and Working with Files

Title Description Participants Textbook

Byte and Character Streams. Reading and Writing Console input and output

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

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

COMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output

Lecture 11.1 I/O Streams

Principles, Models, and Applications for Distributed Systems M

14.3 Handling files as binary files

Performing input and output operations using a Byte Stream

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

Chapter 10. IO Streams

Stream Manipulation. Lecture 11

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

Internet Technology 2/7/2013

Objec&ves. Review. Standard Error Streams

Principles, Models, and Applications for Distributed Systems M

Variables of class Type. Week 8. Variables of class Type, Cont. A simple class:

Reading and Writing Files

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

Lesson 3: Accepting User Input and Using Different Methods for Output

Lecture 7. File Processing

Streams and File I/O

Object-Oriented Programming in the Java language

Today. Book-keeping. File I/O. Subscribe to sipb-iap-java-students. Inner classes. Debugging tools

PIC 20A Streams and I/O

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

Homework 3 Huffman Coding. Due Thursday October 11

Streams and File I/O

Software Practice 1 - File I/O

This Week s Agenda (Part A) CS121: Computer Programming I. The Games People Play. Data Types & Structures. The Array in Java.

Lab 2: File Input and Output

Special error return Constructors do not have a return value What if method uses the full range of the return type?

CN208 Introduction to Computer Programming

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

I/O Streams. Object-oriented programming

CS193j, Stanford Handout #26. Files and Streams

Course Content. Objectives of Lecture 22 File Input/Output. Outline of Lecture 22. CMPUT 102: File Input/Output Dr. Osmar R.

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. Representation of Primitive Java Types. CSE143 Sp

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

File Operations in Java. File handling in java enables to read data from and write data to files

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

ITI Introduction to Computer Science II

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

CS 2113 Software Engineering

Chapter 10 Input Output Streams

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

Web Server Project. Tom Kelliher, CS points, due May 4, 2011

CS September 2017

File Processing in Java

Programming Languages and Techniques (CIS120)

COMP-202: Foundations of Programming. Lecture 22: File I/O Jackie Cheung, Winter 2015

Sri Vidya College of Engineering & Technology Question Bank

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

CPSC 319. Week 2 Java Basics. Xiaoyang Liu & Sorting Algorithms

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Techniques of Java Programming: Streams in Java

Introduction Unit 4: Input, output and exceptions

Chapter 11: Exceptions and Advanced File I/O

Full file at

FILE I/O IN JAVA. Prof. Chris Jermaine

Chapter 12: Exceptions and Advanced File I/O

A sample print out is: is is -11 key entered was: w

Files and IO, Streams. JAVA Standard Edition

COMP200 INPUT/OUTPUT. OOP using Java, based on slides by Shayan Javed

Text User Interfaces. Keyboard IO plus

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

The Java I/O System. Binary I/O streams (ASCII, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

CS112 Lecture: Streams

Programmierpraktikum

Basic Java IO Decorator pattern Advanced Java IO. Java IO - part 2 BIU OOP. BIU OOP Java IO - part 2

Java Input / Output. CSE 413, Autumn 2002 Programming Languages.

COMP-202: Foundations of Programming. Lecture 12: Linked List, and File I/O Sandeep Manjanna, Summer 2015

Character Stream : It provides a convenient means for handling input and output of characters.

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.

תוכנה 1 תרגול 8 קלט/פלט רובי בוים ומתי שמרת

I/O streams. Byte Streams Character Streams InputStream ByteArrayInputStream FileInputStream FilterInputStream

Transcription:

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

I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or a file Output can be to display (screen) or a file Advantages of file I/O» permanent copy» output from one program can be input to another» input can be automated (rather than entered manually) 2

Streams Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.)» it acts as a buffer between the data source and destination Input stream: a stream that provides input to a program Output stream: a stream that accepts output from a program» System.out is an output stream A stream connects a program to an I/O object» System.out connects a program to the screen 3

Binary Versus Text Files All data and programs are ultimately just zeros and ones» each digit can have one of two values, hence binary» bit is one binary digit» byte is a group of eight bits Text files: the bits represent printable characters» one byte per character for ASCII, the most common code» for example, Java source files are text files» so is any file created with a text editor Binary files: the bits represent types of encoded information, such as executable instructions or numeric data» these files are easily read by the computer but not humans» they are not "printable" files actually, you can print them, but they will be unintelligible "printable" means "easily readable by humans when printed" 4

Java: Text Versus Binary Files Text files are more readable by humans Binary files are more efficient» computers read and write binary files more easily than text Java binary files are portable» they can be used by Java on different machines» Reading and writing binary files is normally done by a program» text files are used only to communicate with humans Java Text Files Source files Occasionally input files Occasionally output files Java Binary Files Executable files (created by compiling source files) Usually input files Usually output files 5

Text File I/O Important classes for text file output (to the file)» DataOutputStream» FileOutputStream Important classes for text file input (from the file):» DataInputStream» FileInputStream Note that FileOutputStream and FileInputStream are used only for their constructors, which can take file names as arguments.» DataOutputStream and DataInputStream cannot take file names as arguments for their constructors. To use these classes your program needs a line like the following: import java.io.*; 6

Every File Has Two Names The code to open the file creates two names for an output file» the name used by the operating system out.txt in the example» the stream name outputstream in the example Java programs use the stream name» outputstream in the example 7

Text File Output To open a text file for output: connect a text file to a stream for writing» create a stream of the class DataOutputStream and connect it to a text file For example: DataOutputStream outputstream = new DataOutputStream(new FileOutputStream("out.txt")); Then you can use print and println to write to the file outputstream.println(count + " " + line); The text lists some other useful DataOutputStream methods 8

TextFileOutputDemo Part 1 public static void main(string[] args) A try-block is a block: { outputstream would DataOutputStream outputstream = null; not be accessible to the try rest of the method if it { Opening the file were declared inside the try-block outputstream = new DataOutputStream(new FileOutputStream("out.txt")); } catch(filenotfoundexception e) Creating a file can cause { the FileNotFound- Exception if the new System.out.println("Error opening the file out.txt."); file cannot be created. System.exit(0); } 9

TextFileOutputDemo Part 2 System.out.println("Enter three lines of text:"); String line = null; int count; for (count = 1; count <= 3; count++) { line = field.gettext(); Writing to the file outputstream.println(count + " " + line); } outputstream.close(); Closing the file System.out.println("... written to out.txt."); } The println method is used with two different streams: outputstream and System.out 10

Java Tip: Appending to a Text File To add to a file instead of replacing it, use a different constructor for FileOutputStream: outputstream = new DataOutputStream(new FileOutputStream("out.txt", true)); Second parameter indicates that file should not be replaced if it already exists. Data written to file will be added to the end of the file. Sample code for letting user tell whether to replace or append: System.out.println("A for append or N for new file:"); char ans = field.gettext(); boolean append = (ans == 'A' ans == 'a'); true if user outputstream = new DataOutputStream( enters 'A' new FileOutputStream("out.txt", append)); 11

Closing a File An output file should be closed when you are finished writing to it (and an input file should be closed when you are finished reading from it). Use the close method of the class DataOutputStream (DataInputStream also has a close method). For example, to close the file opened in the previous example: outputstream.close(); If a program ends normally it will close any files that are open. 12

FAQ: Why Bother to Close a File? If a program automatically closes files when it ends normally, why close them with explicit calls to close? Two reasons: 1. To make sure it is closed if a program ends abnormally (it could get damaged if it is left open). 2. A file open for writing must be closed before it can be opened for reading. Although Java does have a class that opens a file for both reading and writing, it is not used in this text. 13

Text File Input To open a text file for input: connect a text file to a stream for reading» use a stream of the class DataInputStream and connect it to a text file» use the FileInputStream class to connect the DataInputStream object to the text file For example: DataInputStream inputstream = new DataInputStream(new FileInputStream("data.txt")); Then:» read lines (Strings) with readline» DataInputStream has no methods to read numbers directly, so read numbers as Strings and then convert them» read a char with read 14

Exception Handling with File I/O Catching IOExceptions IOException is a predefined class File I/O done as described here might throw an IOException You should catch the exception in a catch block that at least prints an error message and ends the program FileNotFoundException is derived from IOException» therefore any catch block that catches IOExceptions also catches FileNotFoundExceptions» errors can be isolated better if they have different messages» so create different catch blocks for each exception type» put the more specific one first (the derived one) so it catches specifically file-not-found exceptions» then you will know that an I/O error is something other than filenot-found 15

Example: Reading a File Name from the Keyboard reading a file name from the keyboard using the file name read from the keyboard reading data from the file public static void main(string[] args) { String filename = null; try { System.out.println("Enter file name:"); filename = SavitchIn.readLineWord(); BufferedReader inputstream = new BufferedReader(new FileReader(fileName)); String line = null; line = inputstream.readline(); System.out.println("The first line in " + filename + " is:"); System.out.println(line); //... code for reading second line not shown here... inputstream.close(); } catch(filenotfoundexception e) { System.out.println("File " + filename + " not found."); System.exit(0); } catch(ioexception e) { System.out.println("Error reading from file " + filename); System.exit(0); } } TextFileInputDemo2 closing the file Chapter 10 Java: an Introduction to Computer Science & Programming - Walter Savitch 16

Reading Words in a String: Using StringTokenizer Class There are DataInputStream methods to read a line and a character, but not just a single word StringTokenizer can be used to parse a line into words» it is in the util library so you need to import java.util.*» some of its useful methods are shown in the text e.g. test if there are more tokens» you can specify delimiters (the character or characters that separate words) the default delimiters are "white space" (space, tab, and newline) 17

Example: StringTokenizer Display the words separated by any of the following characters: space, new line (\n), period (.) or comma (,). String inputline = field.gettext(); StringTokenizer wordfinder = new StringTokenizer(inputLine, " \n.,"); //the second argument is a string of the 4 delimiters while(wordfinder.hasmoretokens()) { System.out.println(wordFinder.nextToken()); } Question 2b Entering "Question,2b.or!tooBee." gives this output: or!toobee 18

Testing for End of File in a Text File When reading text files in Java you can test for a special character that signals the end of the file: When readline tries to read beyond the end of a text file it returns the special value null» so you can test for null to stop processing a text file read returns -1 when it tries to read beyond the end of a text file» the int value of all ordinary characters is nonnegative Neither of these two methods (read and readline) will throw an EOFException. 19

Example: Using Null to Test for End-of-File in a Text File When using readline test for null Excerpt from TextEOFDemo int count = 0; String line = inputstream.readline(); while (line!= null) { count++; outputstream.println(count + " " + line); line = inputstream.readline(); } When using read test for -1 Chapter 9 Java: an Introduction to Computer Science & Programming - Walter Savitch 20