COMPSCI4039: Programming
FileIO and Exceptions
What we¡¯re working towards
Copyright By PowCoder代写 加微信 powcoder
See LoadStudents.java…
¡ñ Loads a comma separated file holding student names and grades into an array of Student objects
¡ñ The file parsing bit is quite straightforward
¡ñ But the exception handling is a bit of a pain.
Exceptions
¡ñ How many of you have seen an Exception?
All of you…
What are exceptions?
¡ñ Exceptions are objects
¡ñ Exceptions are made and thrown when something bad
¡ñ We can catch exceptions in our programs so that we
can make the bad things better
¡ñ Some exceptions have to be caught
¡ð Known as checked exceptions
¡ñ Some don¡¯t have to be caught (the ones you¡¯ve seen)
¡ñ Known as unchecked exceptions
¡ñ Dealing with files requires handling checked
exceptions
¡ñ But we¡¯ll look at unchecked ones first
Unchecked exceptions
¡ñ Unchecked exceptions are common e.g.:
¡ð You try and access an element of an array that doesn¡¯t exist
¡ð You try and convert ¡°Hello¡± into an integer ¡ð ….
¡ñ Normally, they cause some red text to appear, and your program to stop
¡ñ You can also make them happen on purpose using the throw command
public class Throw {
public static void main(String[] args) {
System.out.println(“About to throw an unchecked exception”);
throw new ArrayIndexOutOfBoundsException();
About to throw an unchecked exception
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException
at Throw.main(Throw.java:5)
Throw your own
¡ñ You can also make your own Exception (…exceptions are objects…)
¡ñ To make an unchecked exception, you extend the RuntimeException class
public class MyException extends RuntimeException { }
public class Throw {
public static void main(String[] args) {
System.out.println(“About to throw!”);
throw new MyException(); }
About to throw an unchecked exception
Exception in thread “main” MyException
at Throw.main(Throw.java:5)
¡ñ Exceptions become really useful once you know how to catch them
¡ð Remember: all exceptions can be caught. Some (checked ones) have to be caught.
¡ñ Catching an exception detects that it has happened and allows you to act accordingly.
¡ñ Achieved using try / catch / finally blocks
}catch(
// if code A causes an exception
}finally {
// some code done regardless
import java.util.Random; public class ArrayException {
public static void main(String[] args) { int[] x = new int[10];
Random r = new Random();
int pos = r.nextInt(20); System.out.println(x[pos]);
Simple example
¡ñ This code will (sometimes) cause ArrayIndexOutOfBoundsException to be thrown (when pos >= 10 (the length of the array))
¡ñ We can catch this exception…
import java.util.Random;
public class ArrayExceptionCaught {
public static void main(String[] args) { int[] x = new int[10];
Random r = new Random();
int pos = r.nextInt(20);
System.out.println(x[pos]);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println(“Too big”);
e.printStackTrace();
}finally {
System.out.println(“This happens whatever”); }
¡ñ Now if pos >= 10 the Exception is caught (by the catch statement) and we do something (in this case, prints ¡°Too big¡± and the stack trace)
¡ñ If pos < 10 we don¡¯t enter the catch block
¡ñ Either way we enter the finally block
¡ñ In this case, we could do the same with if / else
¡ñ But in many cases try / catch is much neater (and
compulsory!)
Aside - Random
¡ñ In the last example we used Random
¡ñ Random is a Java class that provides the capability for
generating (pseudo)random numbers.
¡ñ We created an instance of the class:
¡ð Random r = new Random();
¡ñ And then called the nextInt(int max) method to
generate random integers between 0 and max-1
¡ñ It has methods for generating other types (e.g.
COMPSCI4039: Programming
FileIO and Exceptions
A checked exception - FileNotFoundException
¡ñ FileReader is a Java class that allows you to read characters from a file
¡ñ Here¡¯s an excerpt from the Java API
¡ñ It tells us that the constructor throws FileNotFoundException and we
therefore have to catch it
FileReader
FileReader object is created in the try.
Catch catches the Exception (FileNotFoundException) that the FileReader constructor might throw
¡ñ It is the constructor that throws the exception
¡ñ So we have to put the code that makes the FileReader
(new FileReader(filename) etc) into a try block
import java.io.FileNotFoundException; import java.io.FileReader;
public class FR {
public static void main(String[] args) { try {
String fN = "C:\\Users\\ucackxb\\Week5\\students.csv";
FileReader fr = new FileReader(fN);
}catch(FileNotFoundException e) {
e.printStackTrace();
printStackTrace() is a useful method that Exceptions have for debugging
Closing the FileReader
¡ñ FileReader objects need to be closed when we¡¯re finished with them
¡ñ It is good practice to do this in a finally block: it gets closed whatever happens.
¡ñ The API tells us that the close method of FileReader can throw an IOException which we will need to catch
¡ñ We do this in a separate try catch block within the finally of the first try catch block
¡ñ ...and we need to create the FileReader reference outside the first try catch block so that it is in scope
Make the reference here so it is visible in finally
import java.io.FileNotFoundException; import java.io.FileReader;
import java.io.IOException;
public class FR2 {
public static void main(String[] args) { FileReader fr = null;
String fN = "C:\\Users\\ucackxb\\Week5\\students.csv";
fr = new FileReader(fN); }catch(FileNotFoundException e) {
e.printStackTrace();
}finally {
try { fr.close();
}catch(IOException e) {
e.printStackTrace();
Try and close the FileReader, catching the IOException that might be thrown.
FileReader
¡ñ We can now do the actual file reading
¡ñ But first, a couple more useful things about Exceptions...
Catching ¡®higher¡¯ exceptions
¡ñ FileNotFoundExceptioninheritsfromIOExceptionwhichinheritsfrom Exception, which also inherits from Throwable
¡ñ Anywhere where we need to catch FileNotFoundException, we could catch any of these types instead, and it would be caught (this is an example of polymorphism)
This is from the end of our last program. We¡¯ve swapped:
¡ð FileNotFoundException for its super class, IOException
¡ð IOException (second catch statement) for its super-super class
Both of the exceptions we need to catch could be caught as IOException (FileNotFoundException is a sub- class of IOException)
example...
¡ñ This solution is not as neat - it¡¯s good practice to catch exceptions individually
import java.io.FileReader;
import java.io.IOException;
public class FR3 {
public static void main(String[] args) { FileReader fr = null;
String fN = "/Users/simon/Desktop/students.csv"; fr = new FileReader(fN);
// read file
fr.close();
}catch(IOException e) {
e.printStackTrace();
This will catch Exceptions thrown by either the FileReader constructor or the close() method.
Delegating catches
¡ñ If you don¡¯t want to deal with the exception, you can delegate it up to whatever called your method.
¡ñ This is achieved by adding throws
public void myMethod(String a) throws IOException, ArrayIndexOutOfBoundsException {
¡ñ This means you can get rid of all the exception handling in our FileReader by defining our main to throw the exceptions…
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class FR4 {
public static void main(String[] args) throws FileNotFoundException, IOException{ String fN = “C:\\Users\\ucackxb\\Week5\\students.csv”;
FileReader fr = new FileReader(fN);
// some reading
fr.close(); }
Defining methods that throw exceptions can be useful
In this case, it¡¯s just a bit lazy! (useful for quick prototyping) Q: the code above is a bit redundant – what could we remove?
Delegating catches 2
Because myMethod can throw a MyException, it has to be in a try catch block.
public class Delegation {
public static void main(String[] args) {
try { myMethod();
}catch(MyException e) {
e.printStackTrace();
public static void myMethod() throws MyException { // some code
if(new Random().nextInt(10)<=7) {
throw new MyException();
A MyException can be thrown in this method. It doesn¡¯t want to deal with it, so throws it up to the calling method (main).
Order is important
¡ñ Because of polymorphism, multiple catch statements could potentially catch the same Exception:
¡ñ In such cases, which one will catch it?
¡ñ E.g. Where will the FnF exception be caught?
public class ClassQ {
public static void main(String[] args) {
throw new FileNotFoundException();
}catch(IOException e) { System.out.println("IO");
}catch(FileNotFoundException e) { System.out.println("FnF");
Exceptions are caught by the first (top to bottom) catch statement that they can be caught by
In this case, Java will not compile because all FnF exceptions will be caught by the IOException making the line that prints FnF unreachable
COMPSCI4039: Programming
FileIO and Exceptions
Reading from a file
¡ñ Now we¡¯ve sorted out Exception handling (it¡¯s not just a file thing...) we can read from the file.
¡ñ FileReader allows us to read individual characters
¡ñ This is tedious - we use a Scanner to read in complete lines
¡ñ We pass the FileReader to the Scanner when we make it...
// make a filereader object
fr = new FileReader("C:\\Users\\ucackxb\\Week5\\students.csv"); // make a scanner around the filereader Scanner s = new Scanner(fr);
Files and paths
¡ñ When we create a FileReader we will pass it the name of the file.
¡ñ This needs to include the complete path to the file
¡ñ On Mac or Linux it might be: /Users/kevin/Desktop/fileName
¡ñ On the lab machines (Windows) it might be something like this:
¡ð H:\aDirectory\anotherDirectory
¡ñ And remember that \ is a special character so to get a \ you need to use 2!
¡ð StringfileName=¡°H:\\aDirectory\\anotherDirectory\\etc¡±;
Reading from a file
¡ñ We then loop while there are more lines to be read:
// Loop until no lines left
while(s.hasNextLine()) {
// get the next line
String line = s.nextLine();
Reading from a file
¡ñ Each line has the following format: ¡ð
¡ñ We will use the String.split method which splits a String into an array of smaller strings
¡ñ If we ask it to split using a comma, it will give an array of all of the comma separated elements
¡ð Stringline=¡°KevinBryson,38¡±;
¡ð String[] tokens = line.split(¡°,¡±);
¡ð Stringline=¡°KevinBryson,38¡±;
String[] tokens = line.split(¡°,¡±);
Reading from a file
¡ñ Finally, we need to turn the grade into an int (it¡¯s currently a String)
¡ñ The static parseInt() method from the Integer class will do this:
¡ð int grade = Integer.parseInt(tokens[1]);
¡ñ We can now make a new Student object from the name and grade:
¡ð newStudent(tokens[0],grade);
¡ñ And store it into the array (also increasing the number of
¡ð students[nStudents++] = new Student(tokens[0],grade);
Putting it all together
¡ñ See LoadStudents.java Overview:
¡ñ To read from the file we need a FileReader object
¡ñ We give this to a Scanner to get the contents line by
¡ñ We then process each line (I used String.split, you
could also use another Scanner)
¡ñ Around this process we need all of the exception
handling things.
¡ñ We needn¡¯t have done things line by line – could use
any Scanner methods…e.g. next(), nextInt(), etc
COMPSCI4039: Programming
FileIO and Exceptions
Writing to a file
¡ñ Say we now want to sort the students and write them (sorted) to a new file
¡ñ Our Student object has a compareTo method (Comparable interface) so we can use Arrays.sort
¡ñ To write to a file we use a FileWriter object…
¡ñ The same Exception handling is required
¡ñ Once we¡¯ve done that, we can write any String to the
file using the FileWriter¡¯s write() method.
¡ñ See LoadStudents2.java
¡ð [ had to add a getName() method to Student]
BufferedWriter
¡ñ You might see examples that use a BufferedWriter to write to the file
¡ñ It can be beneficial to put things in a buffer (temporary storage) and only write
to the file once there is enough there
¡ñ This is what BufferedWriter does.
¡ñ You can force it to write by flushing the buffer (bw.flush())
¡ñ Data also written when:
¡ð Buffer is full
¡ð BufferedWriter is closed
fw = new FileWriter(outName);
BufferedWriter bw = new BufferedWriter(fw);
// maybe a loop or something
bw.write(newLine);
JFileChooser
¡ñ What if we want to allow the user to specify the file?
¡ñ We could ask them to type in the filename
¡ñ Or we could use a JFileChooser…
JFileChooser
¡ñ JFileChooser is part of the Java Swing GUI library.
¡ñ It includes both open and save windows
¡ñ Very easy to use:
¡ð JFileChooser fc = new JFileChooser();
¡ð int returnVal = fc.showOpenDialog(new JFrame());
¡ñ This will pop up a JFileChooser dialog box
¡ñ returnVal tells you if a file was chosen or not (0 = yes)
¡ñ Access the File object using fc.getSelectedFile();
¡ñ SeeChoosingFiles.java
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com