CS11 Java. Fall Lecture 4

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

Sri Vidya College of Engineering & Technology Question Bank

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

10/7/15. MediaItem tostring Method. Objec,ves. Using booleans in if statements. Review. Javadoc Guidelines

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

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

JAVA - FILE CLASS. The File object represents the actual file/directory on the disk. Below given is the list of constructors to create a File object

Lecture 11.1 I/O Streams

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

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

Programming II (CS300)

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

CS Programming I: File Input / Output

Here is a hierarchy of classes to deal with Input and Output streams.

CS Programming I: File Input / Output

Object-Oriented Programming in the Java language

Exception-Handling Overview

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

PIC 20A Exceptions. Ernest Ryu UCLA Mathematics. Last edited: November 27, 2017

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

Exceptions Handling Errors using Exceptions

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

Java Programming Unit 7. Error Handling. Excep8ons.

CS 200 File Input and Output Jim Williams, PhD

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 11

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

I/O STREAM (REQUIRED IN THE FINAL)

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

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

CS Week 11. Jim Williams, PhD

Assertions and Exceptions Lecture 11 Fall 2005

ITI Introduction to Computing II

16-Dec-10. Consider the following method:

2.6 Error, exception and event handling

ITI Introduction to Computing II

Objec-ves JAR FILES. Jar files. Excep-ons. Files Streams. Ø Wrap up Ø Why Excep-ons? 9/30/16. Oct 3, 2016 Sprenkle - CSCI209 1

CS 3 Introduction to Software Engineering. 3: Exceptions

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions

Data Structures. 03 Streams & File I/O

Lecture 19 Programming Exceptions CSE11 Fall 2013

National University. Faculty of Computer Since and Technology Object Oriented Programming

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

Each command-line argument is placed in the args array that is passed to the static main method as below :

Writing your own Exceptions. How to extend Exception

Programming II (CS300)

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked

PIC 20A Streams and I/O

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

C17: File I/O and Exception Handling

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2015 Lecture 11

Events and Exceptions

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

JAC444 - Lecture 4. Segment 1 - Exception. Jordan Anastasiade Java Programming Language Course

Object-oriented programming in Java (3)

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

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

Programming Languages and Techniques (CIS120)

Errors and Exceptions

School of Informatics, University of Edinburgh

Java. Error, Exception, and Event Handling. Error, exception and event handling. Error and exception handling in Java

JAVA.IO.FILE CLASS. static String pathseparator -- This is the system-dependent path-separator character, represented as a string for convenience.

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

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

Exception Handling. CSE 114, Computer Science 1 Stony Brook University

CSE 331 Software Design & Implementation

6.Introducing Classes 9. Exceptions

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

Object Oriented Programming

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

IT101. File Input and Output

Here is a hierarchy of classes to deal with Input and Output streams.

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

Exceptions. What exceptional things might our programs run in to?

A Quick Tour p. 1 Getting Started p. 1 Variables p. 3 Comments in Code p. 6 Named Constants p. 6 Unicode Characters p. 8 Flow of Control p.

Midterm assessment - MAKEUP Fall 2010

Lab 2: File Input and Output

Exceptions and Working with Files

Exception Handling. Exception Handling

CS 11 java track: lecture 3

CS61B Lecture #12. Today: Various odds and ends in support of abstraction.

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Java Loose Ends. 11 December 2017 OSU CSE 1

Lecture 4: Exceptions. I/O

Software 1 with Java. Recitation No. 7 (Java IO) May 29,

Chapter 11: Exceptions and Advanced File I/O

Software 1 with Java. Recitation No. 9 (Java IO) December 10,

Files and Streams

CS159. Nathan Sprague

CS112 Lecture: Exceptions and Assertions

BBM 102 Introduction to Programming II Spring Exceptions

Chapter 12: Exceptions and Advanced File I/O

Exceptions and Libraries

Programming Languages and Techniques (CIS120)

C16b: Exception Handling

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

I/O Streams. Object-oriented programming

Chapter 12 Exception Handling

Input-Output and Exception Handling

Transcription:

CS11 Java Fall 2014-2015 Lecture 4

Java File Objects! Java represents files with java.io.file class " Can represent either absolute or relative paths! Absolute paths start at the root directory of the filesystem " e.g. C:\Documents and Settings\Donnie Pinkston\Desktop\Foo.java! Note: \ characters must be escaped in Java strings! " e.g. /home/donnie/desktop/foo.java! Relative paths start from the current directory " Can use. to mean the current directory ".. means the parent of the current directory

Java File Objects (2)! java.io.file provides several constants " File.separator is a String containing the name separator that appears in paths! On Windows, set to \\. On Unix variants, set to / " Also File.separatorChar, a char constant! Also have constants for path separators " File.pathSeparator is a String containing the separator between path components! On Windows, set to ;. On Unix variants, set to : " Useful when you must programmatically generate a classpath or other collection of file/directory paths

Creating File Objects! File constructor is very easy to use " File(String pathname)! Specify a relative or absolute path to the file " File(File parent, String child)! Assumes that parent is a directory! Creates a new File object to reference a file child in the directory parent " File(String parent, String child)! Same as previous constructor! These constructors don t test whether the files actually exist!

Examining File Objects! Many helpful methods to examine files, such as: " boolean exists()! Is there a file or directory on the filesystem corresponding to the File object? " boolean isfile()! Is the File object a normal file? (checks that it s not a directory, and also some system-specific checks) " boolean isdirectory()! Is the File object a directory? " boolean canread()! Does the file exist, and can it be read by the application? " boolean canwrite()! Does the file exist, and can it be written by the application? " long length()! Reports a file s length.

Manipulating File Objects! Can perform basic file operations, such as: " boolean delete()! Delete a file, or a directory (if it s empty). Returns true if successful, false if not. " boolean renameto(file dest)! Rename a file or directory to a different location! May not succeed if moving the file across filesystems, or if destination file already exists, etc.

Navigating the Filesystem! Can also use File to navigate the filesystem: " File[] File.listRoots()! Static method that returns an array of File objects specifying the system s root directories " File[] listfiles()! Instance method that returns an array of File objects within a directory " (will talk about Java arrays in a future class)! Can also specify filters to listfiles() method " Implement FilenameFilter or FileFilter interface to exclude files based on some criteria

Java Stream IO! Java provides a stream-based IO mechanism! java.io.inputstream, java.io.outputstream " Abstract base-classes that specify all operations that streams should provide! Usually open an input- or output-stream via some specific mechanism " e.g. open a file and get an input-stream " e.g. open a network connection; get an outputstream for sending, an input-stream for receiving

Java Stream IO (2)! InputStream methods: " read() for reading one or more bytes! A blocking method: will not return until more data is available, or it knows that a read will definitely fail " available() reports how many bytes can be read without blocking " close() closes the input stream! Releases any resources associated with the stream! OutputStream methods: " write() for writing one or more bytes " flush() to force any internal Java write-buffers to be written out to the OS (may be buffered by OS though) " close() closes the output stream

Java Stream IO (3)! InputStream and OutputStream are byte streams " The values actually transferred are bytes " Often not suitable for text-based data! (Particularly locale-specific data.)! java.io.reader and java.io.writer interfaces work with character data " Basically same operations as InputStream and OutputStream, but with char values

Java Stream IO (4)! Java stream API supports composing streams! Example: read lines of a text file FileInputStream fis = new FileInputStream("foo.txt");! FileInputStream derives from InputStream InputStreamReader isr = new InputStreamReader(fis);! Wrap the input-stream with a Reader to read character data BufferedReader br = new BufferedReader(isr);! Add buffering to reader so we can read whole lines of text! (Java stream IO API is a little annoying )

Java Stream IO and Exceptions! File objects report some failures with a boolean result " boolean delete() " boolean renameto(file dest)! Most stream IO operations report failures by throwing exceptions " Usually java.io.ioexception, or some subclass of this exception

Exceptions! Sometimes code can detect an error, but not necessarily resolve it " e.g. a FileInputStream can detect that the file can t be opened, but what should it do?! Several ways to indicate errors to the caller " Return a special error value! unless it s a constructor, which can t return a value! " Throw an exception to signal the error! An exception aborts the current computation " Execution transfers immediately to handler code

Throwing Exceptions! Throwing exceptions is easy: public double computevalue(double x) { if (x < 3.0) { throw new IllegalArgumentException( "x must be >= 3, got " + x); return 0.5 * Math.sqrt(x 3.0);! A new exception object is created and then thrown! Exception is populated with a stack-trace " Specifies where the exception object was created (not where it was thrown ) " Best to create the exception right when you throw it

Throwing Exceptions (2)! When exception is thrown, execution immediately transfers to handler for that exception public double computevalue(double x) { if (x < 3.0) { throw new IllegalArgumentException( "x must be >= 3, got " + x); return 0.5 * Math.sqrt(x 3.0);! For above function, when exception is thrown, no more code inside the function is executed.! Can specify an error message for exceptions " Should indicate what is expected, and what actually happened

Exception Handlers! To handle an exception, code must catch it void main(string[] args) { double x = getdouble(); try { double result = computevalue(x); System.out.println("Result is " + result); catch (IllegalArgumentException e) { System.out.println("Bad input: " + e.getmessage());! Code inside try block could throw an exception! catch block will handle any errors that occur " IllegalArgumentException errors, that is

Exception Handlers (2)! If computevalue() throws, execution transfers immediately to catch-block with same exception type void main(string[] args) { double x = getdouble(); try { double result = computevalue(x); System.out.println("Result is " + result); catch (IllegalArgumentException e) { System.out.println("Bad input: " + e.getmessage()); " No result would be printed; the error is printed instead.

Exception Handlers (3)! To catch exceptions from code that could throw, must enclose that code in a try block " A try block can only handle exceptions that occur within that block of code!! Exception s type governs which catch block actually handles an exception " Specify one or more catch blocks immediately after the try block " First catch block with matching type will handle the exception " After catch block executes, execution resumes after try/catch statement (only one catch runs)

Java Exceptions! Java has restrictions on exception handling: " Only objects of type java.lang.throwable (and subclasses) can be thrown " In general, methods must declare what kinds of exceptions they throw! Another aspect of Java enforcing correctness! Forces programs to handle exceptions, or to explicitly declare what might be thrown

Java Exception Hierarchy Throwable Base-class for all throwable objects in Java Error Serious issues in JVM; apps generally won t handle them Exception Standard run-of-the-mill problems that apps might want to handle RuntimeException Apps may or may not handle these. Usually indicate programming errors. Throwable Error Exception...... RuntimeException...

Checked Exceptions! Checked exceptions: " Any subclass of Exception that doesn t derive from RuntimeException! Methods must specify checked exceptions they throw: import java.io.ioexception; public String getquote() throws IOException {... if (erroroccurred) throw new IOException("An error occurred!"); return quote; " Java compiler checks method s code against specifications " Can also specify runtime exceptions, but not required

Checked Exceptions (2)! A method may specify a base-class of what it throws public String getquote() throws IOException {... " All these exceptions derive from IOException:! UnknownHostException (couldn t resolve hostname)! EOFException (unexpected end of file)! SocketException (general socket problem) " The above method could also throw these without changing its exception specification! Code can also catch the base-class type " e.g. could catch (IOException e) and handle the above exceptions

What Exceptions To Handle?! Java API Documentation indicates which exceptions are thrown " API docs also say when they are thrown! IO and networking libraries can throw many exceptions! Threading libraries also can throw some exceptions! Always very important to handle exceptions gracefully, to make your applications robust!

This Week s Assignment! This week, will add a few new features to your Fractal Explorer " The ability to render multiple fractals! A dropdown combobox will allow users to select which fractal to render " The ability to save the currently displayed fractal image to disk! Both features shouldn t be very hard to build " Can rely on various Java APIs to make these tasks very simple

Multiple Fractals! Most GUI toolkits support dropdown combo-boxes " Allows user to choose from a list of options! Provided by the Swing JComboBox class " Very easy to set up and use " Fires ActionEvents when the selection changes

Saving Images! Also add a button to your user interface, to save the current image! Swing provides two helpful classes: " JFileChooser lets you select a file for opening or saving " JOptionPane can be used to show dialogs when things go wrong

Saving Images (2)! Now there are multiple sources of action events! Generally, want to reduce total number of objects your programs create! Goal: " Implement a single action-listener that can handle events from all sources

Action Commands! Most components that fire ActionEvents also have an action-command field " Use this field to indicate the source s purpose or action JButton savebutton = new JButton("Save Image"); savebutton.setactioncommand("save"); " Other sources get their own action-commands too.! Action-command value is provided in ActionEvent " getactioncommand() method on ActionEvent " Now ActionListener can listen to multiple sources, and perform the proper action based on the action-command

Multiple-Source Action Listeners! Example action-listener implementation: void actionperformed(actionevent e) { String cmd = e.getactioncommand(); if (e.getsource() == fractalchooser) {... // Get the fractal the user selected,... // and display it. else if (cmd.equals("reset")) {... // Reset the fractal image. else if (cmd.equals("save")) {... // Save the current fractal image.