Learn Programming in Java - Lesson 17: File Input/Output

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome back my name is Michael fudge and this is lesson 17 in our learned program in java series in this lesson we'll cover file input and output on the agenda for lesson 17 first we'll talk about the basics of file i/o that is how do you read and write two data files talk about the two formats in which you can read and write to files text files which are human readable data and binary files which are only machine readable then we'll do some examples of some basic text file i/o and we'll do some examples of binary file i/o specifically focusing on serializing the objects that we've made already so let's talk about the basics of text file i/o in Java my argument is if you can do console IO which we've been doing all up until this point you should have no problem implementing text file IO it's pretty much the same thing as a matter of fact when you think of system dot in which we usually think of that as the keyboard but think of that as an input of text and then system.out think of that as an output of text and really you have what's going on now rather than us reading from system in and system out instead we're going to use the the class file and in Java the class file is a representation of a physical file on disk as a matter of fact when you construct an object of class file you usually give it a string that represents the file that you want to use to mimic the print print Lin and print F methods that were used to we will use the print writer class print writer is used to output to a file the same way you write to system out you use print writer and for input we'll continue to use scanner which tends to be the most flexible class for doing input from a text file and this will work the exact same way as you know scanner already instead of using system in will use an object of type file class instead when we create our scanner class an object of our type scanner okay let's jump into a demo in this first demo we'll do something really boring like create a file write some data to it and then open the file back up and read the data back out nothing earth-shattering but at least give you an idea on how file i/o works so that you can kind of build your own examples from there okay Here I am in my NetBeans IDE and I've created a new project called basic file i/o and I have one class called basic file IO Java and I'm going to start writing to a file and then after I write to the file I will read what I wrote back out then I will show you where the file is on disk and I will open it up and show you that it really is a text file and it contains human readable text in it again the difference between a text file and a binary file is the operating system treats a text file as text which is of course human readable and a binary file is binary that is just a series of 1s and 0s and it's no guarantee that it will be human readable let's start by making an object of type file and let's call this test text so the first line that we've added here comes from the package Java i/o and it's a file class and I call the variable file because I'm on creative and I'm going to make a new object of type file and it needs one argument which is the name of the file there it is test text now file is a substitute for system in or system out that we can use with print writer and scanner for example let's write to the file name and age to the file so I need a printwriter to do that I'm going to call it output new printwriter where is this printwriter going to right it's going to right not to system out it's going to write to file file is in essence a reference to test dot txt right you include that package okay output dot print Lin Mike fudge output dot print Lin 42 one important thing to note when you are using file IO is that you have to remember to close the handle to the file this is important so that it releases the file for use by other programs in the operating system something different than when you use standard input an output that is the keyboard in the screen now if you notice I'm getting an error here and that's because I need to use a try this this may throw an exception so I need to catch that exception and I can just follow the advice here if I want or I could do the right thing and surround it with a try/catch this is why we introduced the exceptions unit before we introduced the file i/o unit you need to know something about exceptions before you can correctly handle and address file i/o issues in Java it raises an i/o exception so I want to catch that exception and what should I do when I catch this exception probably do something like this let's print out a message the specific error I'm going to print I'm going to just say error and then % s now we're going to just send an e X and when I send in the object e^x of type io exception it will convert this to a string because of this format specifier so it'll take the exception and then just blurt it out as a string but I'll see it on the console so if some error is to be raised from this operation it will will show it out let me reformat this code so it looks a little better okay so this in essence will write to a file and at this point I can run the program it's not going to do anything exciting except right to the file now you might be wondering where's this file so let's go find it the actual location this file will vary a little bit based on your operating system so here's the best way to find it it's going to be in the same location as your project so if I right-click on here and go to properties in my NetBeans IDE you'll see it says project folder this is the location of that file because I didn't specify any other path so I'm going to copy that project folder and then I'm going to just explore the operating system filesystem and I'm just going to drop that in there with a paste and then there's tests see that and my text file it's human readable and the first line print line Mike fudge that's what was printed second print line 42 that's what was printed so it did exactly what we expected let's write a program to read that file but let's continue our existing program I should say to read that file and then print the met print the data to the console just so we know that we're correctly reading files again so to read a file we need the scanner class and it's going to look similar normally here we'd say system in right well we don't want to read from the keyboard we want to read from that file so I'm going to put in that file and now we can say string name is input dot next line looks very familiar doesn't it except I'm not getting input from the keyboard anymore I'm getting input from this file since I know this is actually an integer I could say nextint here and then I could say int age if I really want to and then I can print them out name % s age % d my name age now I'm getting an error here so once again for this error I need to use my try/catch now what kind of error can be raised here you need to worry about catching the file not found exception because again what if I try to read from this and it's not there that's going to throw an exception I need to handle that exception so I'm just going to repeat my error message of you rather on creative I could say something like please choose a different file or something along those lines but I'm just going to merely handle the error with grace now one important thing is if I didn't want to do a try-catch in here I could force this method to throw those exceptions I could say public static void main throws filenotfoundexception IO exception up here and then that would address the issue as well but I think I'll catch them inside this method and do something with them okay I think I've got it and I think this should do what we expect it should print out my name and age named Mike fudge 842 it's important to note that it is it is reading these from the file and just to prove to you that it is reading them from the file I'm going to go back here to the file Mike fudge 42 right I'm gonna go into this code here which this code here writes to the file and this code here reads from the file if this reads from the file that writes to the file I'm going to take this and just comment it all out so now my program will only read from the file doesn't write to the file so let me run it says Mike fudge age 42 now let me go to my file and let's change this around there we go save my file and when I run it this time it better not say Mike fudge age 42 it better say Kelly Jones age 46 and it does tada see that so as you can see reading and writing a to a file is not that much different than reading and writing to and from the console as a matter of fact that could easily take a lot of the programs that I have written in the previous units and modify them to no longer accept input from system dot in but accept input from a carefully crafted text file so that's really kind of the basics of text file i/o as you can see text file i/o is really no different than the i/o you already know when we get into object serialization in a bit you're going to see that this works a little bit differently and that's because you're taking what you have in memory is an object and then writing it as binary to disk there's lots of ways you can do binary file i/o and I think what I need to emphasize here is the most common thing that we're looking to accomplish with writing to a file and reading from a file is to be able to take our objects that only exist in memory and persist them that is maybe you have an object that holds your application settings you know it's an object of class settings and it holds all sorts of different variables that control how your application works and what you want to do is you want to have a way that those settings can be saved to a file so that the next time the program is run a user doesn't have to REM configure how they want the application to behave right that's a great example of object serialization so object serialization is just a process we use to convert an in-memory object into a series of bytes so they can be written to disk and so we have two concepts we have object to disk we call that serialization and we have taking it off of the disk and putting it into the object that's called D serialization the way this works is if you want your object to be capable to be serialized in other words if you want your object to be serializable all you need to do is implement the serializable interface and then your object will have this capability now that you've got a serializable object how do you actually go about reading or writing that object to file so once again it's going to start with the file class and then from there we're either going to make a file input stream if we want to read it or a file output stream if we want to write it and the input and output streams are telling Java to treat that data file like bytes and not like text from there we will use the object input stream or object output stream to actually do the serialization or D serialization that is taking the object and putting it in the file or taking it out of the file and putting it back in the object again so you need five things to read from a file you need the an object of the file class then you're going to need the file input stream and then the object input stream and ultimately you'll be able to read that serializable class to work the other way you're going to need obviously a file and then the file output stream and object output stream to write that object to the file okay let's get into a really quick demo okay folks here I am in my NetBeans IDE with our next example and in this example I have two Java classes I made one is called student Java and you've seen this example hundreds of times before already in this class the only difference between this implementation of student and other implementations of students as I've added implements serializable and imported a package java io serializable and this tells java that i would like to take this student object and read to and write from a file with it I'd like to serialize it and then here is my sample program and in my sample program all I've done so far is I've made a reference file to students text which does not exist at this point and I have an ArrayList a dynamic collection of type student and I'm calling it students what a great name and then I add three students so if I were to run this program it's not going to do much of anything at this point but if I run it and then put a breakpoint on line 16 you would see that I have this collection students and it's got three actual objects of type student in it so maybe the first thing I want to do is maybe I want to write all three of these students that is write the entire collection to a file let's see if we can do that first so I would like to serialize the collection of students and I sped I spelled cereal eyes wrong but that's going to happen so first thing I'm going to need is a file output stream and I'm going to call it because I'm very uncreated foe that's going to be a new file output Stream with my file and of course I've got my red line here because I need to include the package and now we still have a red line it says unsupported exception file not found exception must be caught or I have to decide to not catch it and then just throw it up here in my main method for example I could just say it was file not found exception right I could just come up here and say well this I'm not going to catch it here but this is going to throw a file not found exception rather lazy yet convenient so if I decide to not catch the exception when the potential file not found exception when this occurs then I need to make sure that the method that this is contained within will graciously throw that exception for someone else to consume I think I'll take that option rather than wrapping it in a try-catch now I need an object output stream I'm going to call this output and that's going to be a new object output stream and it's going to take not the file but the file output stream this is always the pattern the file output stream takes the file the object output stream takes the file output stream as its argument and you can see that this is also complaining about throwing an exception this rows an i/o exception so again rather than surround this with a try-catch I'll just come up here and say well it throws a file not found exception and also me it maybe it'll throw an i/o exception okay now how am I going to write these well it's actually quite easy I'm going to say four for each student I'm going to call it s in my collection of students how about we do this output dot right object which object do I want to write s and of course you always want to clean up after yourself what her parents always told us clean up after yourself that's what I'm telling you now when you use file IO and Java clean up after yourself what does that mean you want to close all references to the actual file itself right so I need to make sure that I output not close so I need to make sure I type output close and of course file output close there we go so this program in essence will make this collection and then this code here from line 19 to 26 will serialize those three objects let's run it nothing exciting happens but now if I go here to my source package there's where my project folder is if I open this up you'll see there's a student's file right there if I open it up this is now a binary file you see when I open it up inside a text editor I don't see anything that makes any sense to me okay I might get lucky and see Dave and Bill in there and Tom right there's there's little hints of things but this is certainly not human readable nor nor is it designed to be what it's designed to do is be a very quick and easy way that Java can write to and read from that file to and from in to objects so yes I just serialized it now let me deserialize it the collect do serialize the file back into the collection okay to do this I'm going to need a file input stream I'm going to call this fi that's going to be a new file input stream using our file then we're going to say object input stream object street using my fee file input okay and there we have it now I need to read into my collection right so I guess rather than cheating and using the same collection let me do this come down here and I'm going to call this students too so you now you know it's a completely different collection and let's do this while true let's say student s is student input dot read object when you read an object it returns an object back I need to cast that object or treat the object that I read as a student before I assign it to an object of type student you need to explicitly cast the object and then let's add it to the collection students - dot add s now what's interesting about reading from an object is you might say well how do I know when I'm done right well when you can no longer read from the object input stream it throws a end-of-file exception so I need to catch that and you see it's not throwing an error because I'm not catching it but this will loop and then actually this goes back to the difference between a user generated exception and a program generated exception this isn't going to be this is going to be a program generated exception so I need to I need to catch this so I'm going to do this so this is really the true pattern you need when you want to read an object input stream that is if you want to deserialize an object you need to do this pattern try try this and some at some point you are going to catch and end-of-file exception and when you do you're done I know it looks kind of goofy but that's how it works so again it's going to loop and it's going to keep reading in the object and putting it in s than adding it reading in the object putting it into s adding it and then soon as it hits an exception that says there's nothing more to read that's end of file so it'll catch that exception and then it'll exit out of the loop because obviously in the try-catch block when the exception is thrown it's going to stop running this code and start running this code so it's really kind of an elegant way to stop looping there is no end of file condition in the object input stream there's just an exception that gets thrown you'll notice also I'm still getting an error here because I need to catch a class not found exception what I'm going to do is I'm just going to do that up here what you're saying when you do this by the way is you're pretty much saying these are the I give up throws especially in the main method you're saying you know if anything happens down here you know just let these exceptions fly and then you'll see them out in the console under normal circumstances if this was some kind of method in a class right we might want to throw these so that they go up to the caller and then the caller can address them with a try-catch but it certainly doesn't make a lot of sense to do this in the main method other than the fact that your teacher is lazy okay so now when I get to this point line 42 I should have a collection of students - that has the three names in it so let's print them out so this is you know again a little goofy but and this doesn't really make a lot of sense but I just wanted to prove to you that I'm not just pulling the wool over your eyes and printing the same thing we already had I actually took this wrote it to a file read it from a file and then put it back into memory and a completely different object and then I'm going to print out that object okay so now this should do something rather uneventful if it works it's going to just print out Tom Dave and Bill do you see that Tom Dave and Bill but really what happened was I had Tom Dave and Bill and memory under students then down here I see realized Tom Dave and bill into the file students text then I deserialized Tom Dave and Bill from students text into another ArrayList students too that I printed out students too and if you really don't believe me I'm sure many of you do believe me but if you don't believe me and I debug this when I hit this breakpoint you'll see I have two collections and memory students this is my original one see there's bill 2.0 and here's students two and that one also has bill to point oh and how did it get in there I read it from this file and there you have it that's file serialization and deserialization what do you need to know and what do you need to remember what you need to remember is that to write to a file to write an object to a file you need the file output stream and the object output stream and the object output stream takes as an argument the file output stream and you just use out you just call the right object method to put that object in the file when you're reading it works kind of in Reverse you put you say input read object and then you have to remember to cast that object to the target type so once again in order to correctly read from a file you have to know what's expected right I expect this file to contain a bunch of students and so that's how I know to cast it as a student and then lastly when when you can read no more from the file it will throw an EO F exception and you have to catch that exception otherwise your program will crash right if I do not catch this exception I will get an error when it cannot read anymore students out of the file they probably don't want that I want the program to continue well this concludes our lesson on Java file programming we learned how to read and write two text files and we learn how to serialize objects thank you very much for watching and I'll catch up with you again next time in the meantime I welcome your questions comments and feedback on YouTube thanks a lot and bye now
Info
Channel: Michael Fudge
Views: 351,981
Rating: undefined out of 5
Keywords: PrintWriter Scanner FileWriter FileReader, Serialization (File Format Genre)
Id: _jhCvy8_lGE
Channel Id: undefined
Length: 28min 41sec (1721 seconds)
Published: Thu Oct 31 2013
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.