Docsity

Advanced Input/Output: Handling Exceptions, Binary Files, and Serializing Objects in Java, Exams of Computer Science

Partial preview of the text

Download Advanced Input/Output: Handling Exceptions, Binary Files, and Serializing Objects in Java and more Exams Computer Science in PDF only on Docsity!

Advanced I/OAdvanced I/O

Exceptions Binary files

Sequential/Random accessSerializing objects

g^

j

ExceptionsExceptions

z^ No matter how good of a programmer you are, you can’t controleverything.everything.

-^ Other users–^ Available memoryFil

ll

ti

-^ File allocation

z^ How do we write a

safe

method that behaves

sanely

even in the

possibility of failure for reasons beyond your control?–^ Exceptions: tell the calling code “Something bad happened. Ifailed.”–^ Any method that take a risk (could fail) should declare that risk whenyou take it so that the failure can be dealt with if it occurs–^ A try/catch block tells the compiler that you

know

you are calling

something that might fail at run-time and what to do if it

does

fail.

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Generating an ExceptionGenerating an Exception

public

class

RobotException

extends

Exception{

public

RobotException

{^ super(“Error:

Bad

robot!”;}

end

class

RobotException

} //

end

class

RobotException

public

class

RobotOnFireException

extends

RobotException{

end

class

RobotOnFireException

public

class

CrazedRobotException

extends

RobotException{

public

void

useRobot

(Order

order)

throws

RobotException

boolean

taskPerformed

=^ giveRobotOrder(Order

order);

i^

public

class

CrazedRobotException

extends

RobotException{

end

class

CrazedRobotException

if^ (!taskPerformed())

if^ (isRobotOnFire())

throw

new

RobotOnFireException();

} if^ (

b^

{^

h^

d^ b

i^ ()

z^ Exceptions declare a problem, they don’t handle/fix it! That’s for the

if^ (RobotIQ

>^ 200)

{^ throw

new

CrazedRobotException();

} } //^ end

useRobot Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

p^

p^

,^

y

person who called the code to deal with!

Stack TraceStack Trace

Exception

in^

thread

“main”

java.lang.StringIndexOutOfBoundsException:String

index

out

of^

range:

at^ java.lang.String.charAt(Unknown

Source)

at^ Coordinate.getStatus

(Coordinate:

at^ Ship.getLocation

(Ship:

at^ GameBoard.checkTarget

(GameBoard.java:

at^ GameBoard.play

(GameBoard.java:

at^ Main.main

(Main.java:

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Taking responsibility: Try/CatchTaking responsibility: Try/Catch

z^ The compiler needs you toacknowledge that you’ve

try^

{ // potentially

risky

code

acknowledge

that you ve

taken responsibility forhandling an exception z Throwing it up the call

}^ catch

(Exception

e)^

//^ do

this

if^

it^ fails

Throwing

it up the call

stack acknowledges itwithout doing anything atthat level

try^

{ robot.useRobot(order); }^ catch

(RobotOnFireException

e)^

z^ Try/Call allows you to dealwith the problem and put itto bed

useFireExtinguisher(robot); }^ catch

(CrazedRobotException

e)^

startVirus(robot); } catch

(Exception

e)^

z^ If an exception passedthrough main, JVM willshut down

}^ catch

(Exception

e)^

System.out.println(“Robot

“is^

out^

of^ control.

Run!”;

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Handling a potentialHandling a potential IOException

IOException

public static void main (String[] args) {boolean validFile;do {

String filename = getFilenameFromUser();File fileHandle = new File (filename);Scanner inputFile = null;validFile =

true; try {^ inputFile = new Scanner (fileHandle); } catch (Exception e) {^ System.out.println("Error opening input file: " + filename);validFile = false; }} until (validFile);processFile(inputFile); } // end method main

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

}^ // end method main

Writing to a binary fileWriting to a binary file

import java.io.FileOutputStream;import java.io.DataOutputStream;… public void storeToFile(ArrayList numberList) {

try {FileOutputStream fs = new FileOutputStream(filename);DataOutputStream output = new DataOutputStream(fs);for (int number : numberList) {for (int number : numberList) {

output.writeInt (number);} output.close ();

} catch (Exception ex) {ex.printStackTrace();} } // end method storeToFile written to

Breaks into bytes

chained to

Writes bytesto file

chained to

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Value

DataOutputStream

FileOutputStream

File

Reading from a binary fileReading from a binary file

import java.io.FileInputStream;import java.io.DataInputStream;… public ArrayList readFromFile() {

ArrayList numberList = new ArrayList();boolean endOfFile = false;try {FileInputStream fs =

new FileInputStream(filename);

FileInputStream fs =

new FileInputStream(filename);

DataInputStream input = new DataInputStream(fs);while (!endOfFile) {numberList.add( input.readInt() );} } catch (Exception ex) {if (ex instanceof EOFException) { endOfFile = true; }else {ex.printStackTrace();}} input.close();input.close();

} // end method readFromFile^ written to

Breaks into bytes

chained to

Reads bytesto file

chained to

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Value

DataOutputStream

FileOutputStream

File

Reading/Writing from aReading/Writing from a RandomAccessFile

RandomAccessFile

import java.io.RandomAccessFile;public class Main {public static void main (String[] args) throws Exception {

final int SIZE_OF_INT_IN_BYTES = 4;RandomAccessFile file =

new RandomAccessFile("Data.dat","rw");

file.writeInt(7000);file writeInt(102); file.writeInt(102);file.writeInt(123456);file.seek(1 * SIZE_OF_INT_IN_BYTES);System.out.println( file.readInt() );file.close();} // end method main } // end class Main

Breaks into bytesReads/writes fileR^ d^

A^

Fil^

chained to

read, write, seek

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Value

RandomAccessFile

File

Serializing objectsSerializing objects

z^ How can we store/load an object between runs? z^ An instance of an object is really just:z^ An instance of an object is really just:

-^ The specific values of the instance variables (its state)–^ Stored in a specific order somewhere in the heap–^ With a reference that tells you where to find the structure

z^ If the instance variables are all primitive values, this is easy z^ If the instance variables contain object references (aggregation), then thespecific values of the aggregate objects are

also

part of the object’s

effective state. z Essentially, to store a complex object, we need to flatten it out and all theobjects it knows about (and so on) to a “flat” savable representation. z This process is known as

serialization

z^ In Java, classes which implement java.io.Serializable can be serialized

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

,^

p^

j

Example: Deck of CardsExample: Deck of Cards

// class header and statepublic class Deckimplements Serializable {

// class methodspublic Deck () {for (String suit : suitList) {

static final String[] suitList ={"Club","Diamond","Heart","Spade"};static final String[] rankList =

for (String rank :

rankList) {

cardList.add(new card(rank,suit));} // for each rank } // for each suit} // end constructor

static final String[] rankList ={"Ace", "Two", "Three", "Four",“Five”, "Six", "Seven", "Eight","Nine", "Ten", "Jack", "Queen","King"};

} // end constructorpublic void showDeck () {for (Card card: cardList) {

System.out.println(card);

ArrayList cardList =

new^

ArrayList();

} // for each card} // end method showDeck

bli^

i^

id^

i^ ( i^

[]^

) {

public static void main (String[] args) {

Deck deck = new Deck();deck.storeToFile("deckFile.dat");deck = deck.getFromFile("deckFile.dat");deck.showDeck (); Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

();

} // end main

Saving/Serializing an objectSaving/Serializing an object

import java.io.Serializable;import java.io.FileOutputStream;import java.io.ObjectOutputStream;… public void storeToFile(String filename) {

try {FileOutputStream fs = new FileOutputStream(filename);FileOutputStream fs = new FileOutputStream(filename);ObjectOutputStream os = new ObjectOutputStream(fs);os.writeObject (this);os.close ();} catch (Exception ex) {ex.printStackTrace();} } // end method storeToFile written to

serializes object,breaks into bytes

chained to

Writes bytesto file

chained to

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Object

ObjectOutputStream

FileOutputStream

File