ø the problem ø aims and objectives ø research methodology ø
10-exceptions files streams 2 Jar (Java Archive) Files • Archives of Java files • Package code...
-
Upload
truongdang -
Category
Documents
-
view
220 -
download
1
Transcript of 10-exceptions files streams 2 Jar (Java Archive) Files • Archives of Java files • Package code...
9/30/16
1
Objec-ves• Jarfiles
• Excep-onsØ WrapupØ WhyExcep-ons?
• Files• Streams
Oct3,2016 Sprenkle-CSCI209 1
JARFILES
Oct3,2016 Sprenkle-CSCI209 2
9/30/16
2
Jar(JavaArchive)Files• ArchivesofJavafiles• Packagecodeintoaneatbundletodistribute
Ø Easier,fastertodownloadØ Easierforotherstouse
• jar command:create,view,andextractJarfilesØ Workssimilarlytotarjar cf myapplication.jar *.class
• Runitusingjavajava -jar myapplication.jar
Oct3,2016 Sprenkle-CSCI209 3
Jar/TarCommands• Commonop-ons:
• Commonuse:Ø jar cfz archive.jar.gz arch_directoryØ jar xfz archive.jar.gz
Oct3,2016 Sprenkle-CSCI209 4
Option/Operations Meaning
f The name of the archive file c Create an archive file x Extract the archive file v Verbose z Zip (compress) t Table of contents (list contents)
9/30/16
3
Jarfile:Metadata• JarfileincludesaspecialmetadatafilewiththepathMETA-INF/MANIFEST.MFØ SayhowJarfileisusedØ jar createsadefaultmetadatafile,ifnotspecified
Oct3,2016 Sprenkle-CSCI209 5
Jarfile:Metadata• ExamplemetadatafilethatallowsyoutoexecutetheJARwithjava
• Tocreatethejarfile:jar cmf myManifest myapplication.jar *.class
• Runitusingjavajava -jar myapplication.jar
Oct3,2016 Sprenkle-CSCI209 6
Specifying the metadata file
Manifest-Version: 1.0Main-Class: MyApplication
Note the newline
9/30/16
4
Crea-ngJarFilesinEclipse• ExportàJavaàJarfile
Ø Op-onstocreateaMANIFEST.MFfileØ Op-onstoincludesourcefilesoronlyclassfiles
• ShouldsubmitassignmentsthiswayØ Mustincludesourcefiles
• Lookforcheckbox
Oct3,2016 Sprenkle-CSCI209 7
EXCEPTIONS
Oct3,2016 Sprenkle-CSCI209 8
9/30/16
5
Discussion:WhyCheckedandUncheckedExcep-ons?
• Whydowehaveexcep-onsthatthecompilerdoesn’tforcetheprogrammertocheck?Ø Thinkaboutexamplesofuncheckedexcep-ons(ArrayOutOfBoundsException, NullPointerException, ClassCastException)andwhenthoseexcep-onscanoccur
Oct3,2016 Sprenkle-CSCI209 9
MethodsandExcep-onsExample• BufferedReader hasmethodreadLine()
Ø Readsalinefromastream,suchasafileornetworkconnec-on
• Methodheader:
• Interpre-ngtheheader:readLine willØ returnaString(ifeverythingwentright)Ø throwanIOException(ifsomethingwentwrong)
Oct3,2016 Sprenkle-CSCI209 10
public String readLine() throws IOException
PartofAdver-sing
9/30/16
6
Adver-singCheckedExcep-ons• Adver-sing:inJavadoc,documentunderwhatcondi-onseachexcep-onisthrownØ @throws tag
• Examplesofwhenyourmethodshouldadver-sethecheckedexcep-onsthatitmaythrowØ Yourmethodcallsamethodthatthrowsacheckedexcep-on
Ø Yourmethoddetectsanerrorinitsprocessinganddecidestothrowanexcep-on
Oct3,2016 Sprenkle-CSCI209 11
JavadocGuidelinesabout@throws• Alwaysreportifthrowcheckedexcep-ons• Reportanyuncheckedexcep-onsthatthecallermightreasonablywanttocatchØ Excep-on:NullPointerExceptionØ Allowscallertohandle(ornot)Ø Documentexcep-onsthatareindependentoftheunderlyingimplementa-on
• Errorsshouldnotbedocumentedastheyareunpredictable
Oct3,2016 Sprenkle-CSCI209 12
9/30/16
7
WhattodowithaCaughtExcep-on?• Dumpthestackadertheexcep-onoccurs
Ø Whatelsecanwedo?
• Generally,twoop-ons:1. Catchtheexcep-onandrecoverfromit2. Passexcep-onuptowhoevercalledit
Oct3,2016 Sprenkle-CSCI209 13
ToThroworCatch?• Problem:lower-levelexcep-onpropagateduptohigher-levelcode
• Example:userentersaccountinforma-onandgetsexcep-onmessage“fieldexceedsallowedlengthindatabase”Ø LostcontextØ Lower-leveldetailpollu-nghigher-levelAPI
Oct3,2016 Sprenkle-CSCI209 14
Solution: higher-levels should catch lower-level exceptions �and throw them in terms of higher-level abstraction
GUI
DB
…
Excep-onhere
Handled here
9/30/16
8
Excep-onTransla-on
• Specialcase:Excep-onChainingØ Whenhigher-levelexcep-onneedsinfofromlower-levelexcep-on
Oct3,2016 Sprenkle-CSCI209 15
try {// Call lower-level abstraction
}catch (LowerLevelException ex) {
// log exception …throw new HigherLevelException(…);
}
try {// Call lower-level abstraction
}catch (LowerLevelException cause) {
// log exception …throw new HigherLevelException(cause);
}
Most standard Exceptions have this
constructor
Summary:MethodsThrowingExcep-ons• APIdocumenta-ontellsyouifamethodcanthrowanexcep-onØ Ifso,youmusthandleit
• Ifyourmethodcouldpossiblythrowanexcep-on(bygenera-ngitorbycallinganothermethodthatcould),adver-seit!Ø Ifyoucan’thandleeveryerror,that’sOK…letwhoeveriscallingyouworryaboutit
Ø However,theycanonlyhandletheerrorifyouadver-setheexcep-onsyoucan’tdealwith
Oct3,2016 Sprenkle-CSCI209 16
9/30/16
9
ProgrammingwithExcep-ons• Excep-onhandlingisslow
• Useonebigtry blockinsteadofnes-ngtry-catch blocksØ SpeedsupExcep-onHandlingØ Otherwise,codegetstoomessy
• Don'tignoreexcep-ons(e.g.,catch blockdoesnothing)Ø Bemertopassthemalongtohighercalls
Oct3,2016 Sprenkle-CSCI209 17
try {}catch () { }try {}catch () { }
try {try {}catch () { }
}catch () { }
try {……
}catch () { }
Crea-ngOurOwnExcep-onClass• Trytoreuseanexis-ngexcep-on
Ø Matchinnameaswellasseman-cs
• IfyoucannotfindapredefinedJavaExceptionclassthatdescribesyourcondi-on,implementanewExceptionclass!
Oct3,2016 Sprenkle-CSCI209 18
9/30/16
10
Oct3,2016 Sprenkle-CSCI209 19
Crea-ngOurOwnExcep-onClass
public class FileFormatException extends IOException {public FileFormatException() {
}
public FileFormatException(String message) {super(message);
}
// other 2 standard constructors…}
• Cannowthrowexcep-onsoftypeFileFormatException
What happens in this constructor implicitly?
Is this a checked or unchecked exception?
GuidelinesforCrea-ngYourOwnExcep-onClasses
• Includeaccessormethodstogetmoreinforma-onaboutthecauseoftheexcep-onØ “failure-captureinforma-on”
• Checkedoruncheckedexcep-on?Ø Checked:forcesAPIusertohandleBUTmoredifficulttouseAPI• Hastohandleallcheckedexcep-ons
Ø Usecheckedexcep-onifexcep-onalcondi-oncannotbepreventedbyproperuseofAPIandAPIusercantakeausefulac-onaderward
Oct3,2016 Sprenkle-CSCI209 20
9/30/16
11
Oct3,2016 Sprenkle-CSCI209 21
Discussion:BenefitsofExcep-ons• Beentalkingaboutdetails…
• WhydoesJavahaveexcep-onsaspartofthelanguage?
• WhydoesJavaaddsomefeaturesthatPythondoesn’thave?
Oct3,2016 Sprenkle-CSCI209 22
BenefitsofExcep-ons• Forceerrorchecking/handling
Ø Otherwise,won’tcompileØ Doesnotguarantee“good”excep-onhandling
• EasedebuggingØ Stacktrace
• Separateserror-handlingcodefrom“regular”codeØ ErrorcodeisincatchblocksatendØ Descrip-vemessageswithexcep-ons
• PropagatemethodsupcallstackØ Letwhoever“cares”abouterrorhandleit
• Groupanddifferen-ateerrortypes
9/30/16
12
FILES
Oct3,2016 Sprenkle-CSCI209 23
java.io.FileClass• Representsafileordirectory• Providesfunc-onalitysuchas
Ø StorageofthefileonthediskØ Determineifapar-cularfileexistsØ WhenfilewaslastmodifiedØ RenamefileØ Remove/deletefileØ …
Oct3,2016 Sprenkle-CSCI209 24
9/30/16
13
MakingaFileObject• Simplestconstructortakesfullfilename(includingpath)Ø Ifdon’tsupplypath,Javaassumescurrentdirectory(.)
Ø CreatesaFile objectrepresen-ngafilenamed“chicken.data”inthecurrentdirectory
Ø Doesnotcreateafilewiththisnameondisk
Oct3,2016 Sprenkle-CSCI209 25
File f1 = new File("chicken.data");
Oct3,2016 Sprenkle-CSCI209 26
Files,Directories,andUsefulMethods• AFile objectcanrepresentafileoradirectoryØ Directoriesarespecialfilesinmostmodernopera-ngsystems
• UseisDirectory()and/orisFile()fortypeoffileFileobjectrepresents
• Use exists()methodØ Determinesifafileexistsonthedisk
9/30/16
14
Oct3,2016 Sprenkle-CSCI209 27
MoreFileConstructors• Stringforthepath,Stringforfilename
• Filefordirectory,Stringforfilename
File f2 = new File("/csdept/local/courses/cs209/handouts","chicken.data");
File dir = new File("/csdept/local/courses/cs209/handouts");
File f4 = new File(dir, "chicken.data");
Oct3,2016 Sprenkle-CSCI209 28
“Break”anyofJava’sPrinciples?
9/30/16
15
Oct3,2016 Sprenkle-CSCI209 29
java.io.File Class• 25+methods
Ø ManipulatefilesanddirectoriesØ Crea-ngandremovingdirectoriesØ Making,renaming,anddele-ngfilesØ Informa-onaboutfile(size,lastmodified)Ø Crea-ngtemporaryfilesØ …
• SeeonlineAPIdocumenta-on
FileTest.java
SCANNERjava.u-l.
Oct3,2016 Sprenkle-CSCI209 30
9/30/16
16
Oct3,2016 Sprenkle-CSCI209 31
java.util.Scanner• New(er)classforhandlinginput
Ø SinceJava1.5• Manyconstructors
Ø Readfromfile,inputstream,string…
• ManymethodsØ nextXXXX (int,long,line)Ø Skippingpamerns,matchingpamerns,etc.
Scanner sc = new Scanner(System.in);
Scanners• Breaksitsinputintotokensusingadelimiterpamern,whichmatcheswhitespace
• Convertsresul-ngtokensintovaluesofdifferenttypesusingnextXXX()
• Canchangetokendelimiterfromdefaultofwhitespace
• AssumesnumbersareinputasdecimalØ Canspecifyadifferentradix
Oct3,2016 Sprenkle-CSCI209 32
What is “delimiter pattern”?What is “whitespace”?
9/30/16
17
Oct3,2016 Sprenkle-CSCI209 33
UsingScanners• UsenextXXX() toreadfromit…
long tempLong;
// create the scanner for the consoleScanner sc = new Scanner(System.in);
// read in an integer and a Stringint i = sc.nextInt();String restOfLine = sc.nextLine();
// read in a bunch of long integerswhile (sc.hasNextLong()) {
tempLong = sc.nextLong(); }
UsingScanner
Oct3,2016 Sprenkle-CSCI209 34
public static void main(String[] args) {
// open the Scanner on the console input, System.inScanner scan = new Scanner(System.in);
scan.useDelimiter("\n"); // breaks up by lines, useful for // console I/O
System.out.print("Please enter the width of a rectangle: ");int width = scan.nextInt();
System.out.print("Please enter the height of a rectangle: ");int length = scan.nextInt();
System.out.println("The area of your square is " + length * width +
".");} ConsoleUsingScannerDemo.java
Simplified version of online example
9/30/16
18
Output
Oct3,2016 Sprenkle-CSCI209 35
This program calculates the area of a rectangle.
Please enter the width of a rectangle (as an integer): the number is 1Incorrect input.Please enter the width of a rectangle (as an integer): 1 2Incorrect input.Please enter the width of a rectangle (as an integer): 2Please enter the height of a rectangle (as an integer): 3The area of your rectangle is 6.
Read in as one token
Scanners&Excep-ons• ScannersdonotthrowIOExceptions!
Ø Forasimpleconsoleprogram,main()doesnothavetodealwithorthrowIOExceptions
Ø RequiredwithBufferedReader/InputStreamReader combina-on
• ThrowsInputMismatchExceptionwhentokendoesn’tmatchpamernforexpectedtypeØ e.g.,nextLong()calledwithnexttoken“AAA”Ø RuntimeException(nocatchingrequired)
Oct3,2016 Sprenkle-CSCI209 36
How do you prevent such errors?
9/30/16
19
Consoleclass• GetaConsoleobjectusingSystem.console()
• Has some useful methods for requesting passwords
• Issue: does not work through an IDE
Oct3,2016 Sprenkle-CSCI209 37
ConsoleUsingConsoleDemo.java
STREAMS
Oct3,2016 Sprenkle-CSCI209 38
9/30/16
20
Oct3,2016 Sprenkle-CSCI209 39
Streams• Javahandlesinput/outputusingstreams,whicharesequencesofbytes
input stream: an object from which we can read a sequence of bytesabstract class: java.io.InputStream
Oct3,2016 Sprenkle-CSCI209 40
Streams• Javahandlesinput/outputusingstreams,whicharesequencesofbytes
output stream: an object to which we can write a sequence of bytesabstract class: java.io.OutputStream
9/30/16
21
JavaStreams• MANY(80+)typesofJavastreams• Injava.io package• Whystreamabstrac-on?
Ø Informa-onstoredindifferentsourcesisaccessedinessen-allythesameway• Examplesources:file,onawebserveracrossthenetwork,string
Ø Allowssamemethodstoreadorwritedata,regardlessofitssource• CreateanInputStreamorOutputStreamoftheappropriatetype
Oct3,2016 Sprenkle-CSCI209 41
Oct3,2016 Sprenkle-CSCI209 42
java.io ClassesOverview• Twotypesofstreamclasses,basedondatatype:Byte,Text
• Abstractbaseclassesforbinarydata:
• Abstractbaseclassesfortextdata:
InputStream OutputStream
Reader Writer
9/30/16
22
Oct3,2016 Sprenkle-CSCI209 43
ByteStreams
AbstractBaseClasses
Shaded: Read to/write from data sinksWhite: Does some processing
• For binary data• In java.io package
Oct3,2016 Sprenkle-CSCI209 44
CharacterStreams
AbstractBaseClasses
Shaded: Read to/write from data sinksWhite: Does some processing
• For Text• In java.io package• Handle any character in
Unicode set
9/30/16
23
Oct3,2016 Sprenkle-CSCI209 45
ConsoleI/O• Output:
Ø System.outisaPrintStream object• Input
Ø System.in isanInputStream objectØ Throwsexcep-onsifformatofinputdataisnotcorrect• Handleintry/catch
Opening&ClosingStreams• Streamsareautoma/callyopenedwhenconstructed
• Closeastreambycallingitsclose() methodØ CloseastreamassoonasobjectisdonewithitØ Freeupsystemresources
Oct3,2016 Sprenkle-CSCI209 46
9/30/16
24
Reading&Wri-ngBytes• Abstractparentclass:InputStream
Ø abstract int read()• readsonebytefromthestreamandreturnsit
• Concreteinputstreamclassesoverrideread()toprovideappropriatefunc-onalityØ e.g.,FileInputStream’s read()readsonebytefromafile
• Similarly,OutputStreamclasshasabstractwrite() towriteabytetothestream
Oct3,2016 Sprenkle-CSCI209 47
Oct3,2016 Sprenkle-CSCI209 48
Reading&Wri-ngBytes
• read()andwrite()areblockingopera-onsØ Ifabytecannotbereadfromthestream,themethodwaits(doesnotreturn)un-labyteisread
• available():getthenumberofbytesthatareavailableforreading
• Exampleuse:
int bytesAvailable = System.in.available();if (bytesAvailable > 0)
System.in.read(byteBuffer);