so in the previous video we started work on remapping our code and we manage to
create a locationsp class and we using a static initialization block to make sure
that our data as ypu can see their on line 15 and down to line 41 is only
actually created once and again we're taking the functionality under the main class
in terms of creating our locations and put it into this locations class
but it would make more sense to read from a file rather than hard coding this
in Java like this and there's only a few locations in this sample but the full
games actually got a 140 locations and the exits connecting then together are actually
quite complex so storing that information in a file is a better solution so the first
step we need here to do this is to write the data out to a file now the code in the static
initialization block is executed when the class is loaded and that means that all
the data is gonna be available by the time we are able to execute any methods in the
class as a result that means that we can create a main method to write
out the locations and exits data to files now one of the simplest ways to do that
is using a file writer object so let's give that a go so in the locations
class itself I'm gonna create a static method a main method as we've done
before.....and let's start by writing some code so....
....
....and we'll just call the text....
...and will look at that error shortly so for.....
....
..so the code here again we're gonna fix those
errors shortly the code at the moment is quite simple so it creates a file writer object
passes the file name as a parameter to the constructor then uses the right method to
write data to a file then of course once all the data has been written to a file the
file is close as you can see on line 21 now that last step is actually
very important and failing to close streams can really cause problems such as
resource leaks rather than and loc files so if an output file is not closed then the
data can become corrupted or the file remain locked so that no other process is able to
use it in actual fact it's so important that Java 7
has introduced a much neater way of dealing with stream to ensure that they're
actually correctly closed and will be getting to that and using that soon for
know we need to understand why they're actually are errors in the code
each line that involves our file writer was showing the same error and If I just hover over it unhandled
exception java.io.IOException so I mentioned that theirs two
categories of exceptions in Java checked and unchecked exceptions they
work in the same way exactly the same way the difference is that you can't
ignore checked exceptions so IOexception is a checked exception so in
other words our code is not allowed to just ignore it so we really have to deal
with it in some way and until we do the program's not even going to compile so
now we know how to handle exceptions we could just catch
the exception which will fix the problem
so lets start by doing that we are just going to create a try block after the file writer
variable is initialise for first time....
....
.....
....
....so that actually fixes the error and for
now and the program will actually run now so I'm gonna have to right click this time to
make sure we are running the locations.main and not running the other main.java
in the the actual main class so we are actually running the main method within
our locations.java so running that notice now that locations.text has been created
and we can open it in Java in IntelliJ rather to examine the contents and if I close down the
windows so we can see more you noticed its got a location ID a comma and
then the actual description that continues on we got another location ID
another command and another description and so on and so forth
that's pretty much all there is to writing data to the stream one thing I
didn't do which I should really fix now before we go too much further I should
actually have an end of line character so we're I actually write the code here
after the get description you really want to go and put and end of line so I'm gonna
add a plus...and run again that should overwrite the existing
file we've got and make it a little bit easier to look at so now that its finished
executing
close that down and have a look at our location.txt file and their you go its a lot easier to read this time
location i'd command and the actual description that moves to a new lines and
then we can see the other locations
that's it that's pretty much all their is to writing data to to stream the
stream is opened in this case by passing a file name to the file writers constructor
you can see on line 19 the data is then written on line 21 using the for loop to go through each
location that we've got and then the stream is closed on line 23
there is a problem with this code though and we have to add a little bit more complexity
so the problem is that the error in the loop that writes the data will cause the catch
block to be entered skipping over the call to the close method so in other words you can
see on line 21 if we had some errors there its going to skip this line 23 which
means the files isn't going to be closed and its gonna skip straight to the catch block
on line 25 which we may not want and ordinarily when dealing with files we would
not want to skip leaving a file open like that even if there was an error so basically
as a result the file was not gonna be handled or properly closed so to handle
situations like this you know when there's clean up code that absolutely must be
executed no matter what the Java exception handy mechanism also has a
finally block and theirs an exception raise in the try block the code in the catch
block will for that exception will be executed but then regardless of what happened the finally
block is also executed so you can be certain by using the finally block that the
code in their is always gonna be executed
you know as long as the JVM itself doesn't crash which of course is very
unlikely so a try block itself must have either have a catch or a finally block
and it need not have both but it must have at least one or the other so in fact soon I'm
gonna be removing that catch blocks so we can just have try and finally and that is
actually quite common when dealing with I/O operations so better way to code this then
would be to call the close method in a finally block so let's have a look at
doing that so under the catch we can put....
....
...but that then introduces
another error and if hover over it that error and have a look we got a java.ioexception error
so unfortunately closed itself also throws an IOException so we once again
get an unhandled exception error and then we have to wrap the call to close in its
own try catch block so we want to be very careful not to cause more
exceptions in the try block so will also checked that the loc
file variables is not null before attempting to call its close method so go ahead and do
that
so add a try here so...
...and what will do here is just to make sure that we're not going to potentially have other
problems we are gonna put a test here just to make sure that the loc file...
...then and only then we are gonna try and close it...this type of defensive program
really makes programming really make sense particularly in situations like this
when you really don't want something to crash really want to be sort of a fairly sure
and fairly certain that the code is going to be as resilient as possible so it
doesn't crash will actually put a message in their...
...
then the IOException we just are gonna do an e.printStacktracke we don't do anything else we have finally seen how
to write data to an output stream in java which is good so we will just run this
again just to make sure that it does work and finally block as you can see attempting to close
loc file we didn't get any errors and we still got our locations file here
still being written to disk which is good so it seems to be working
so I've actually covered quite a lot their including introducing the finally
block as I mentioned that is really an essential part of exception handling
now up until Java 7 the code in our locations main class was pretty much the standard
template for writing data to a stream and reading from a stream looks very
similar to that but Java 7 introduced an improvement that actually makes the
code quite a bit neater but before looking at that i'm gonna actually gonna cause an
exception just so we can see the exception handling in action
now there's quite a few ways to break IO Code but all 3 operating systems we could
set locations.txt to read only son Linux and OSX we could change
ownership to root you can also specify an invalid path to a file
attempting to create a file on disk drive that does not exist on Windows or in an invalid
volume in Linux and also the OSX thre easiest way here is to just delete the file we have written and
created a directory with the same name before running the program
again and that will actually work on all three operating system so let's
look at doing that so we can actually purposely get it to actually come up
with an error first is come up here and just right click that and click on
reveal in finder go into their take a note of the location where this is, I'm going to
delete it actually what I'm going to do is just going to copy the file name and I'm gonna
need that shortly
and delete the location.txt in my case I'm gonna move to trash you just do whatever
is equivalent to your operating system and just to make this real and a bit weird
we are gonna click on file new folder and it will be a similar thing for your operating system and call the folder
locations.txt so in this case OSX is saying are you sure you want to
make the folder.txt sort of recognises that's a problem so click on add because we do
want it to be in txt we want to be exactly the same and it is actually a folder as you can see so you want
to make sure when you're creating this on Windows or Linux that you actually are
creating a folder not just another file so definitely create a folder as you can see their
so when we run the program we should actually get an error because of course it won't be
able to create a file because it's already folder their with the same name
so run that and yes we did actually managed to get an error and you can see it tells us
quite clearly java.io file not found exception locations.txt is a
directory so you make it something so similar you should get something
very similar in your operating system if you're not running Mac OS X
the bottom line here is that its telling us that it can't create the file
and you can see that it was in the catch block and also went to the finally block
as well so obviously both our bits of code we're actually triggered when it
came up with an error so you might be wondering why is the file not found exception why is that
been caught
when we've actually only look for IOExceptions in our code well the reason for that file not found exception
is actually a subclass of IOException and as a results its caught by our catch block
and we can see the message as can see in the run window to the right hand side
in catch block printed and of course we can also see the final block code as well which
I mentioned now you may see the message from the finally block appeared before
the stack trace rather than after it that's really result of the way of the result
of the way that the stack traces is generated the finally block is executed
after catch you may also send a message from the catch block in amongst a stack
trace but the programs output will be printed in the order it happens but the
stack trace will appear when its good and ready basically so notice here that
there's no attempt to close the file because remember we had this message here
attempting to close location file or loc file that doesn't appear anywhere so
that actually wasn't attempted and the reason that wasn't attempted was because
loc file was set to NULL on line 19 then we got this code on line 21
trying to create a new object that failed so therefore loc file was still null
and consequently we didn't try and close the file and of course was never created in
the first place so you can see why it can be very useful to have this code here to test
for null before trying to actually do something because of course if we hadn't done
that we would have got a null pointer exception because the loc file wasn't a valid object so before moving on it's
going to go back to that folder again so come up to the project and click on
reveal in finder again I'm going to go in to my folder and then delete the folder locations.txt
so we can use that again move to trash do whatever the equivalent is
for Windows and Linux if you're on one of those machines if we run it again we should
find it is now working again now our code is working again normally you can see locations.txt on the
screen alright I'm gonna actually finished this video here in the next video we are gonna
start out with a mini challenge and then we are gonna look at enhancing our code and
using some other functions built into Java for reading and writing file so see you
in the next video