Java I/O and Exceptions

Similar documents
INPUT AND OUTPUT STREAMS

What is an I/O Stream?

Stream Classes and File I/O

public static void main(string[] args) { System.out.println("hello, world"); } }

13 File Output and Input

Event-Driven Programming

Simple Java I/O. Streams

Using Files as Input/Output in Java 5.0 Applications

Chapter 10. A stream is an object that enables the flow of data between a program and some I/O device or file. File I/O

Files and input/output streams

Creating a Simple, Multithreaded Chat System with Java

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Lecture J - Exceptions

CS506 Web Design and Development Solved Online Quiz No. 01

Building a Multi-Threaded Web Server

JAVA - FILES AND I/O

D06 PROGRAMMING with JAVA

WRITING DATA TO A BINARY FILE

CS 111 Classes I 1. Software Organization View to this point:

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

READING DATA FROM KEYBOARD USING DATAINPUTSTREAM, BUFFEREDREADER AND SCANNER

Readings and References. Topic #10: Java Input / Output. "Streams" are the basic I/O objects. Input & Output. Streams. The stream model A-1.

What are exceptions? Bad things happen occasionally

1 of 1 24/05/ :23 AM

D06 PROGRAMMING with JAVA

Programming in Java

Socket-based Network Communication in J2SE and J2ME

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

Input / Output Framework java.io Framework

Network Communication

CS 1302 Ch 19, Binary I/O

CS 121 Intro to Programming:Java - Lecture 11 Announcements

Java from a C perspective. Plan

File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Lesson: All About Sockets

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

B.Sc (Honours) - Software Development

public static void main(string args[]) { System.out.println( "f(0)=" + f(0));

Java Programming Language

COSC 6397 Big Data Analytics. Mahout and 3 rd homework assignment. Edgar Gabriel Spring Mahout

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

ECE 122. Engineering Problem Solving with Java

FILE I/O IN JAVA. Prof. Chris Jermaine Prof. Scott Rixner

Network/Socket Programming in Java. Rajkumar Buyya

Java Interview Questions and Answers

Fundamentals of Java Programming

Introduction to Java. Module 12: Networking (Java Sockets) Prepared by Costantinos Costa for EPL 233. ΕΠΛ233 Αντικειμενοστρεφής Προγραμματισμός 1

Explain the relationship between a class and an object. Which is general and which is specific?

Reading Input From A File

Learning Outcomes. Networking. Sockets. TCP/IP Networks. Hostnames and DNS TCP/IP

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

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

Software Construction

How To Write A Program For The Web In Java (Java)

CS170 Lab 11 Abstract Data Types & Objects

Quick Introduction to Java

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Transparent Redirection of Network Sockets 1

gomobi Traffic Switching Guide Version 0.9, 28 September 2010

AP Computer Science Java Subset

Programming Methods & Java Examples

Computing Concepts with Java Essentials

java Features Version April 19, 2013 by Thorsten Kracht

Mail User Agent Project

TP1 : Correction. Rappels : Stream, Thread et Socket TCP

Master of Sciences in Informatics Engineering Programming Paradigms 2005/2006. Final Examination. January 24 th, 2006

Homework/Program #5 Solutions

!"# $ %!&' # &! ())*!$

Java Network Programming. The java.net package contains the Socket class. This class speaks TCP (connection-oriented protocol).

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

Chapter 2: Elements of Java

Java SE 8 Programming

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

Java SE 7 Programming

Object-Oriented Programming in Java

Bandwidth-limited systems. Chapter 8 Bandwidth-Limited Systems. Two flavors of limited bandwidth - 1. Outline of the chapter

Today s Outline. Computer Communications. Java Communications uses Streams. Wrapping Streams. Stream Conventions 2/13/2016 CSE 132

IBM Tivoli Workload Scheduler Integration Workbench V8.6.: How to customize your automation environment by creating a custom Job Type plug-in

Specialized Programme on Web Application Development using Open Source Tools

Inside the Java Virtual Machine

Course Intro Instructor Intro Java Intro, Continued

Application Development with TCP/IP. Brian S. Mitchell Drexel University

Java SE 7 Programming

Programming Languages CIS 443

Division of Informatics, University of Edinburgh

Copyright. Restricted Rights Legend. Trademarks or Service Marks. Copyright 2003 BEA Systems, Inc. All Rights Reserved.

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Prof. Edwar Saliba Júnior

Logging in Java Applications

Question R11.3. R11.3 How do you open a file whose name contains a backslash, like c:\temp\output.dat?

Socket Programming in Java

Java Programming Fundamentals

This example illustrates how to copy contents from one file to another file. This topic is related to the I/O (input/output) of

AP Computer Science File Input with Scanner

Crash Course in Java

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Have both hardware and software. Want to hide the details from the programmer (user).

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Transcription:

Java I/O and Exceptions CS1316: Representing Structure and Behavior Writing to a Text File We have to create a stream that allows us access to a file. We re going to want to write strings to it. We re going to have to handle things going wrong exceptional events like the filename being wrong or the disk failing. Here s how Input and Output Streams - java.io Java handles input and output through sequential streams of bits Programs can read from a stream or write to a stream File String Source or Destination Array 100110 Byte Data Character Data Program Standard Input and Output We have been using System.out.println to print output to a PrintStream (standard output). System.out.println( First Name: + firstname); There is also a System.err PrintStream that can be used to write to the standard error output. System.err.println( Error: no file name given ); You can use System.in to read a byte or bytes from an InputStream (standard input). int numgrades = System.in.read(); 1

Chaining Input and Output Classes Often input or output classes are chained Passing one type of input/output class to the constructor for another One common thing is to chain a processing class with a data sink class Like a BufferedReader or BufferedWriter and a FileReader or FileWriter new BufferedReader(new FileReader(fileName)); Exceptions Exceptions are disruptions in the normal flow of a program. Exception is short for exceptional event. The programmer is required to handle checked exceptions in Java like trying to read from a file that doesn t exist Run-time exceptions do not have to be handled by the programmer like trying to invoke a method on a object reference that is null Children of RuntimeException Try and Catch Use a try & catch clause to catch an exception code that can cause exceptions catch (ExceptionClassName varname) { catch (ExceptionClassName varname) { You can catch several exceptions Make the most general one last All exceptions are children of the class Exception Try and Catch: If the file isn t there What if you want to know if a file isn t found That you are trying to read from If this occurs you might want to use a JFileChooser to let the user pick the file You also want to handle any other error code that can cause the exception catch (FileNotFoundException ex) { code to handle when the file isn t found catch (Exception ex) { 2

Catching Exceptions A catch clause will catch the given Exception class and any subclasses of it. So to catch all exceptions use: You can print the error message code that can throw the exception and the stack catch (Exception e) { trace (the list of all System.err.println( Exception: + e.getmessage()); currently running System.err.println( Stack Trace is: ); methods) e.printstacktrace(); You can create your own exceptions by subclassing Exception or a child of Exception. The optional finally clause A try and catch statement can have a finally clause Which will always be executed Will happen if no exceptions Will happen even if exceptions occur code that can cause the exception catch (FileNotFoundException ex) { code to handle when the file isn t found finally { code to always be executed Writing to a File Use a try-catch clause to catch exceptions Create a buffered writer from a file writer writer = new BufferedWriter(new FileWriter(fileName)); Write the data writer.write(data); Close the buffered writer writer.close(); Reading Lines of Character Data Enclose the code in a try and catch clause Catch FileNotFoundException if the file doesn t exist And you may want to give the user a chance to specify a new file Catch Exception to handle all other errors Create a buffered reader from a file reader for more efficient reading File names are relative to the current directory Loop reading lines from the buffered reader until the line is null Do something with the data Close the buffered reader 3

Reading from File Example BufferedReader reader = null; String line = null; // try to read the file // create the buffered reader reader = new BufferedReader(new FileReader(fileName)); // loop reading lines till the line is null (end of file) while ((line = reader.readline())!= null) { // do something with the line // close the buffered reader reader.close(); catch (Exception ex) { // handle exception Adding an Output File to WolfDeerSimulation /* A BufferedWriter for writing to */ public BufferedWriter output; /** * Constructor to set output to null **/ public WolfDeerSimulation() { Opening the File /** * Open the input file and set the BufferedWriter to speak to it. **/ public void openfile(string filename){ // Try to open the file // create a writer output = new BufferedWriter(new FileWriter(filename)); catch (Exception ex) { System.out.println("Trouble opening the file " + filename); // If any problem, make it null again Changing the time loop // Let's figure out where we stand... System.out.println(">>> Timestep: "+t); System.out.println("Wolves left: "+wolves.getnext().count()); System.out.println("Deer left: "+deer.getnext().count()); // If we have an open file, write the counts to it if (output!= null) { // Try it try{ output.write(wolves.getnext().count()+"\t"+deer.getnext().count()); output.newline(); catch (Exception ex) { System.out.println("Couldn't write the data!"); System.out.println(ex.getMessage()); // Make output null so that we don't keep trying 4

After the timing loop // If we have an open file, close it and null the variable if (output!= null){ try{ output.close(); catch (Exception ex) {System.out.println("Something went wrong closing the file"); finally { // No matter what, mark the file as not-there Running the Simulation with a File Welcome to DrJava. > WolfDeerSimulation wds = new WolfDeerSimulation(); > wds.openfile("d:/cs1316/wds-run1.txt") > wds.run(); Finding the file in Excel Adding Labels for the Chart 25 20 15 10 Wolves Deer 5 0 1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49 5