Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

00JavaReviewPart04Slides

The document provides an overview of handling exceptions and file input/output (I/O) in programming. It explains how to create, use, and handle exceptions, as well as the structure of file systems and methods for reading and writing files. Additionally, it covers the use of streams, buffers, and specific classes like PrintWriter and Scanner for file operations.

Uploaded by

dragoboostet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

00JavaReviewPart04Slides

The document provides an overview of handling exceptions and file input/output (I/O) in programming. It explains how to create, use, and handle exceptions, as well as the structure of file systems and methods for reading and writing files. Additionally, it covers the use of streams, buffers, and specific classes like PrintWriter and Scanner for file operations.

Uploaded by

dragoboostet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Even More

Programming Review
Exceptions
and
File I/O
• Provides a means to alert and handle Syntax for Creating an Exception
exceptional run-time events public class <<Exception identifier>> extends <<Existing Exception>>
• 3 Elements {
//Constructors
– Creating Exceptions public <<Exception identifier>>()
– Using Exceptions {
– Handling Exceptions super(“<<Exception Message>>”);
}
• Creating Exceptions }
– “Extending” existing Exception
– Only create Constructors that sets the Exception Example
Message public class DivideByZeroException extends Exception

• Using Exceptions {
public DivideByZeroException()
– Method Definition uses “throws” to indicate {

which Exceptions may occur }


super(“Divided by Zero Exception: Attempted to divide by Zero”);

– Use the reserved word “throw” followed by a }


constructor when the Exception occurs
• Provides a means to alert and handle Syntax for Using an Exception
exceptional run-time events <<Method definition>> throws <<Exception>>, …
• 3 Elements {

– Creating Exceptions throw new <<Exception Constructor>>;
– Using Exceptions }
– Handling Exceptions
• Creating Exceptions
– “Extending” existing Exception
– Only create Constructors that sets the Exception Example
Message public void calculateValue() throws DivideByZeroException, UnknownOpException

• Using Exceptions {

– Method Definition uses “throws” to indicate if(denominator == 0)

which Exceptions may occur …


throw new DivideByZeroException();

– Use the reserved word “throw” followed by a if(opNotRecognized())


constructor when the Exception occurs throw new UnknownOpException();
}
• Handling Exceptions Syntax for Using an Exception
try
• Try and Catch {
<<Method(s) that throws exceptions>>
– Methods that throw exceptions need to be }
enclosed in this catch(<<Exception Type>> e)
{
– When an Exception occurs in the “try” body it <<Handle the Exception>>
is immediately handled by the most }

appropriate “catch” Example


– Catch’s need to be ordered from most specific
try
{
calculateValue();

to least specific }
catch(DivideByZeroException e)
{

• Finally is an optional block of code that


e.printStackTrace();
}
catch(UnknownOpException e)
{

always runs after a try-catch }


e.printStackTrace();

catch(Exception e)
{
e.printStackTrace();
}
• File Input and Output (I/O) allows a program File System Example
to both read and write files to the secondary
storage root

• File Systems C:\

– Organize Data in Secondary Storage Java\

• Directory – Tree Structure Project\


• Folders – Containers for Files
src\
• Root is the starting point
– Address (File Path) ReadingFile.java

• Absolute (C:\Folder\Folder\...) bin\

• Relative (.\Folder or ..\Folder) ReadingFile.class

• Java Project’s Root Directory someFile.txt


– Contains a source (“SRC”) folder D:\
– Contains the bytecode (“BIN”) folder
– Put files in a Project’s Root Directory
• File Input and Output (I/O) allows a program File System Example
to both read and write files to the secondary
storage root

• File Systems C:\

– Organize Data in Secondary Storage Java\

• Directory – Tree Structure Project\


• Folders – Containers for Files
src\
• Root is the starting point
– Address (File Path) ReadingFile.java

• Absolute (C:\Folder\Folder\...) bin\

• Relative (.\Folder or ..\Folder) ReadingFile.class

• Java Project’s Root Directory someFile.txt


– Contains a source (“SRC”) folder D:\
– Contains the bytecode (“BIN”) folder Absolute Path
– Put files in a Project’s Root Directory C:\Java\Project\someFile.txt
• File Input and Output (I/O) allows a program File System Example
to both read and write files to the secondary
storage root

• File Systems C:\

– Organize Data in Secondary Storage Java\

• Directory – Tree Structure Project\


• Folders – Containers for Files
src\
• Root is the starting point
– Address (File Path) ReadingFile.java

• Absolute (C:\Folder\Folder\...) bin\

• Relative (.\Folder or ..\Folder) ReadingFile.class

• Java Project’s Root Directory someFile.txt


– Contains a source (“SRC”) folder D:\
– Contains the bytecode (“BIN”) folder Relative Path
– Put files in a Project’s Root Directory .\someFile.txt
• File Format Common File Formats
– How is information grouped • Plain Text
– Readable words
• Header Data
– Separated by Spaces (single space(s), tabs, end line)
• Body Data – <<word>><<space>…
– How information is Separated • Tab Delimited
– Information separated by Tabs (‘\t’) and end lines (‘\n’)
• Character / Byte length
– Spread Sheet
• Delimiters / Separators • Rows are end lines
• Columns are Tabs
• Plain Text Files – <<information>>\t<<information>>\t…<<information>>\n
• Comma Separated
– Readable Information
– Information separated by Commas (‘,’) and end lines (‘\n’)
– Only Files used in this Course – Spread Sheet
• Rows are end lines
• Binary Files • Columns are Tabs
– <<information>>,<<information>>,…<<information>>\n
– Information stored in Bytes
• Streams and Buffers Stream and Buffer Example
– A Stream is a Sequence of Data
– Buffers provide space to temporarily hold
information Memory

– Buffers holds Streamed information until



“flushed” Program Console

– Generally one direction System.out.println(“Enter
a number”);
• System.out int i = keyboard.nextInt();
… …
– Standard System output Stream
• System.in
– Standard System input Stream …
• Streams and Buffers Stream and Buffer Example
– A Stream is a Sequence of Data
– Buffers provide space to temporarily hold
information Memory

– Buffers holds Streamed information until



“flushed” Program Console
… Enter a number
– Generally one direction System.out.println(“Enter Stream BUFFER
a number”);
• System.out int i = keyboard.nextInt();
… …
– Standard System output Stream
• System.in BUFFER

– Standard System input Stream …


• Streams and Buffers Stream and Buffer Example
– A Stream is a Sequence of Data
– Buffers provide space to temporarily hold
information Memory

– Buffers holds Streamed information until



“flushed” Program Console
… Enter a number
– Generally one direction System.out.println(“Enter BUFFER 4
a number”);
• System.out int i = keyboard.nextInt();
… …
– Standard System output Stream
• System.in BUFFER

– Standard System input Stream …


• PrintWriter Syntax
– Class that creates an object that can write to files //Print Writer Construction to Create / Overwrite a file
PrintWriter <<pwID>> =
– Need to “import java.io.*” to use the type new PrintWriter(
– Construction and use need to be enclosed in a try- new FileOutputStream(
new File(<<path+filename>>)));
catch block //Print Writer Construction to Append to Existing file
• Similar to System.out PrintWriter <<pwID>> =
new PrintWriter(
– Streams information to a file new FileOutputStream(
– Useful Methods new File(<<path+filename>>),true));
//Printing a new line
• print(<<String value>>);
<<pwID>>.println(<<String value>>);
• println(<<String value>>); //Printing to same line
• Always CLOSE the file’s Stream <<pwID>>.print(<<String value>>);
//Closing the PrintWriter Stream
– Resource Leak <<pwID>>.close();
– Ensures all information has been saved (“flushed”)
• Scanner Syntax
– Scans any stream (File I/O, System.in, Network, //Scanner construction to read a file
Scanner <<fsID>> = new Scanner(new File(<<path+filename>>));
Strings)
– Need to “import java.util.*” to use the type //Reading and storing an entire line (until the end line ‘\n’)
<<strVar>> = <<fsID>>.nextLine();
– Construction and use, for files, need to be
enclosed in a try-catch block //Reading and storing the String until the next space (any kind)
– All previous methods can be utilized <<strVar>> = <<fsID>>.next();

• Files are read left to right THEN top to bottom //Reading and storing to the next integer encountered
– Just like the console you cannot go backwards <<intVar>> = <<fsID>>.nextInt();

• Always CLOSE the file’s Stream //Close the Scanner


– Resource Leak <<fsID>>.close();

– Ensures all information has been saved (“flushed”)


• Use the type Scanner • Reading a Plain Text File
1. Open the file
• Make sure the file’s path is correct
2. Read word by word (use method “.next()”)
– Use relative paths 3. Process the information
– Put files in Project’s root directory 4. Repeat Step 2 until the end of the file has been
• Know the File Format reached

– How is the information grouped


• Reading a Tab Delimited
1. Open the file
– How is the information separated
2. Read an entire line (use method “.nextLine()”)
• Files are read left to right then top to 3. Split the line using Tabs
bottom 4. Check if the information is valid
– Cannot go backwards 5. Process the information
6. Repeat Step 2 until the end of the file has been
• Always close the Scanner reached
Plain Text
Example
… File
while(fileScanner.hasNext())
{
String next = fileScanner.next();

}
… File
while(fileScanner.hasNext())
{
String next = fileScanner.next();

}
… File
while(fileScanner.hasNext())
{
String next = fileScanner.next();

}
… File
while(fileScanner.hasNext())
{
String next = fileScanner.next();

}
… File
while(fileScanner.hasNext())
{
String next = fileScanner.next();

}
… File
while(fileScanner.hasNext())
{
String next = fileScanner.next();

}
… File
while(fileScanner.hasNext())
{
String next = fileScanner.next();

}
… File
while(fileScanner.hasNext())
{
String next = fileScanner.next();

}
… File
while(fileScanner.hasNext())
{
String next = fileScanner.next();

}
… File
while(fileScanner.hasNext())
{
String next = fileScanner.next();

}
… File
while(fileScanner.hasNext())
{
String next = fileScanner.next();

}
Exceptions
and
File I/O

You might also like