HST 952. Computing for Biomedical Scientists Lecture 8

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

Streams and File I/O

Dynamic Data Structures

Simple Java Input/Output

1.00 Lecture 30. Sending information to a Java program

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

CS 251 Intermediate Programming Java I/O Streams

PIC 20A Streams and I/O

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

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

Java Input/Output. 11 April 2013 OSU CSE 1

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

Data Structures. 03 Streams & File I/O

Introduction Unit 4: Input, output and exceptions

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

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

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

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

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

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

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

Lecture 11.1 I/O Streams

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

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

CSPP : Introduction to Object-Oriented Programming

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

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

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

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

Exceptions and Working with Files

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

Streams and File I/O

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

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

Darshan Institute of Engineering & Technology for Diploma Studies

Streams and File I/O

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

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

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

IT101. File Input and Output

Object-Oriented Programming Design. Topic : Streams and Files

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

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

Classes Basic Overview

Principles of Computer Science I

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

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

I/O Streams. Object-oriented programming

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

Full file at

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

CN208 Introduction to Computer Programming

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

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

Programming Languages and Techniques (CIS120)

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

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

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

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

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

COT 3530: Data Structures. Giri Narasimhan. ECS 389; Phone: x3748

CS193j, Stanford Handout #26. Files and Streams

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

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

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

Lecture 7. File Processing

Streams and File I/O

File I/O Array Basics For-each loop

Input-Output and Exception Handling

Files and IO, Streams. JAVA Standard Edition

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

Text User Interfaces. Keyboard IO plus

Dining philosophers (cont)

Objec&ves. Review. Standard Error Streams

Programming Languages and Techniques (CIS120)

CS1092: Tutorial Sheet: No 3 Exceptions and Files. Tutor s Guide

Java Programming Lecture 9

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

Programmierpraktikum

Sri Vidya College of Engineering & Technology Question Bank

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

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

Active Learning: Streams

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

1993: renamed "Java"; use in a browser instead of a microwave : Sun sues Microsoft multiple times over Java

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

Object-Oriented Programming in the Java language

CSC 1214: Object-Oriented Programming

File Processing in Java

needs to be reliable, easy to change, retarget efficiency is secondary implemented as interpreter, with virtual machine

ITI Introduction to Computer Science II

Welcome to CIS 068! 1. GUIs: JAVA Swing 2. (Streams and Files we ll not cover this in this semester, just a review) CIS 068

Software Practice 1 - File I/O

FILE I/O IN JAVA. Prof. Chris Jermaine

Lab 5: Java IO 12:00 PM, Feb 21, 2018

14.3 Handling files as binary files

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

Introduction to Programming Using Java (98-388)

Transcription:

Harvard-MIT Division of Health Sciences and Technology HST.952: Computing for Biomedical Scientists HST 952 Computing for Biomedical Scientists Lecture 8

Outline Vectors Streams, Input, and Output in Java Programming examples

Vectors We can think of a vector as an array that can get larger or smaller when a program is running Data structure - a construct that allows us to organize/aggregate data An array is a static data structure A vector is a dynamic data structure

Arrays versus Vectors Arrays Vectors Bad: Good : Size is fixed when declared Size is not fixed Inefficient storage: can use a Better storage efficiency: a partially full array, but space partially full vector may be has been allocated for the allocated just the space it needs full size If one more value needs to be If one more value needs to added past the maximum size be added past the maximum the vector size increases size the array needs to be automatically redeclared Good: Bad: More efficient (faster) Less efficient (slower) execution execution Elements must be class types Elements can be of any type (primitive types not allowed)

Using Vectors Vectors are not automatically part of Java they are in the util library you must import java.util.* Create a vector with an initial size of 20 elements: Vector v = new Vector(20);

Vector Initial Capacity vs. Efficiency Choosing the initial size of a vector is an example of a tradeoff making it too large wastes allocated memory space making it too small slows execution it takes time to resize vectors dynamically Solution? optimize one at the expense of the other or make good compromises choose a size that is not too big and not too small

Vector Syntax The idea is the same as for arrays, but the syntax is different As with arrays, the index must be in the range 0 to size-of-thevector Array: a is a String array Vector: v is a vector a[i] = "Hi, Mom!"); String temp = a[i]; v.setelementat("hi, Mom!", i); String temp = (String)v.elementAt(i); Instead of the index in brackets and = for assignment, use vector method setelementat with two arguments, the value and the index Use vector method elementat(int index) to retrieve the value of an element Note: the cast to String is required because the base type of vector elements is Object

Vector Methods The vector class includes many useful methods: constructors array-like methods, e.g. setelementat & elementat methods to add elements methods to remove elements search methods methods to work with the vector's size and capacity, e.g. to find its size and check if it is empty a clone method to copy a vector see section 10.1 of Savitch text for more details

More Details About Vectors Vectors put values in successive indexes addelement is used to put initial values in a vector new values can be added only at the next higher index You can use setelementat to change the value stored at a particular index setelementat can be used to assign the value of an indexed variable only if it has been previously assigned a value with addelement

Base Type of Vectors The base type of an array is specified when the array is declared all elements of arrays must be of the same type The base type of a vector is Object elements of a vector can be of any class type in fact, elements of a vector can be of different class types it is usually best to have all elements in a vector be the same class type to store primitive types in a vector they must be converted to a corresponding wrapper class

More Details About Vectors The following code looks very reasonable but will produce an error saying that the class Object does not have a method named length: Vector v = new Vector() String greeting = "Hi, Mom!"; v.addelement(greeting); System.out.println("Length is " + (v.elementat(0)).length()); String, of course, does have a length method, but Java sees the type of v.elementat(0) as Object, not String Solution? Cast v.elementat(0) to String: System.out.println("Length is " + (String)(v.elementAt(0)).length();

Vector Size Versus Vector Capacity Be sure to understand the difference between capacity and size of a vector: capacity is the declared size of the vector the current maximum number of elements size is the actual number of elements being used the number of elements that contain valid values, not garbage remember that vectors add values only in successive indexes Loops that read vector elements should be limited by the value of size, not capacity, to avoid reading garbage values

Increasing Storage Efficiency of Vectors A vector automatically increases its size if elements beyond its current capacity are added But a vector does not automatically decrease its size if elements are deleted The method trimtosize() shrinks the capacity of a vector to its current size so there is no extra, wasted space the allocated space is reduced to whatever is currently being used To use storage more efficiently, use trimtosize() when a vector will not need its extra capacity later

More Details About Vectors The method clone is used to make a copy of a vector but its return type is Object, not Vector of course you want it to be Vector, not Object This just makes otherv another name for the vector Cast it to Vector v (there is only one copy of the vector object and it now Vector v = new Vector(10); has two names referring to Vector otherv; the same location/address in otherv = v; memory) Vector otherv2 = (Vector)v.clone(); So, what do you do? This creates a second copy of v with a different name, otherv2 and a different address in memory

Protecting Private Variables Be careful not to return addresses of private vector variables, otherwise calling methods can access them directly "Information Hiding" is compromised To protect against it, return a copy of the vector use clone as described in the previous slide But that's not all: if the elements of the vector are class (and not primitive) types, they may not have been written to pass a copy they may pass their address so additional work may be required to fix the accessor methods (have accessor methods return clones)

Programming example

Input/Output (I/O) Overview 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)

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 System.in is an input stream A stream connects a program to an I/O object System.out connects a program to the screen System.in connects a program to the keyboard

Binary Versus Text Files All data and programs are ultimately just zeros and ones In 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" In binary files: the bits represent other 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 intelligible to a human when printed

Binary Versus Text 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

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

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 e.g., out.txt the stream name e.g., outputstream Java programs use the stream name

Text File Output Binary files are more efficient for Java to process, but text files are readable by humans Java allows both binary and text file I/O To open a text file for output: connect a text file to a stream for writing e.g., create a stream of the class PrintWriter and connect it to a text file

Text File Output For example: PrintWriter outputstream = new PrintWriter(new FileOutputStream("out.txt")); Then you can use print and println to write to the file (convenient) The text lists some other useful PrintWriter methods

Closing a File An output file should be closed when you are done writing to it (and an input file should be closed when you are done reading from it) Use the close method of the class If a program ends normally it will close any files that are open

Closing 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 (the file could get damaged if it is left open). 2. A file that has been opened for writing must be closed before it can be opened for reading.

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 BufferedReader and connect it to a text file use the FileReader class to connect the BufferedReader object to the text file For example: BufferedReader inputstream = Then: new BufferedReader(new FileReader("data.txt")); read lines (Strings) with BufferedReader s readline method BufferedReader has no methods to read numbers directly, so read numbers as Strings and then convert them read a single char with BufferedReader s read method

Input File Exceptions A FileNotFoundException is thrown if the file is not found when an attempt is made to open a file Most read methods throw IOException we have to write a catch block for it If a read goes beyond the end of the file an EOFException is thrown

Handling IOException IOException cannot be ignored either handle it with a catch block or defer it with a throws-clause Put code to open a file and read/write to it in a try-block and write a catch-block for this exception : catch(ioexception e) { } System.out.println( Problem );

Testing for the End of an Input File A common programming situation is to read data from an input file but not know how much data the file contains In these situations you need to check for the end of the file There are three common ways to test for the end of a file: 1. Put a sentinel value at the end of the file and test for it. 2. Throw and catch an end-of-file exception. 3. Test for a special character that signals the end of the file (text files often have such a character).

Testing for End of File in a Text File There are several ways to test for end of file. For reading text files in Java you can use this one: 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

Programming example Reading input from one file and writing output to another

Reading Parts of a String There are BufferedReader 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)

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

Warning: Overwriting a File Opening a file creates an empty file Opening a file creates a new file if one does not already exist Opening a file that already exists eliminates the old file and creates a new, empty one data in the original file is lost How to test for the existence of a file and avoid overwriting it is covered in section 9.3 of the text, which discusses the File class

The File Class Acts like a wrapper class for file names A file name like "out.txt" has only String properties But a file name of type File has some very useful methods exists: tests to see if a file already exists canread: tests to see if the operating system will let you read a file FileInputStream and FileOutputStream have constructors that take a File argument as well as constructors that take a String argument

Summary Text files contain strings of printable characters; they look intelligible to humans when opened in a text editor. Binary files contain numbers or data in non-printable codes; they look unintelligible to humans when opened in a text editor. Java can process both binary and text files for I/O

Summary Always check for the end of the file when reading from a file. The way you check for end-of-file depends on the method you use to read from the file. A file name can be read from the keyboard into a String variable and the variable used in place of a file name.

Programming example Want to create a simple parser that can read a boolean expression typed from the keyboard of the form: true and true true and false true or true true or false not true not false, etc. and print out the truth value of the expression

Chapter 9 Chapter 10 Read