Simple Java I/OPrologueStreamsHow to do I/OWhy Java I/O is hardOpening a streamExample of opening a streamUsing a streamExample of using a streamManipulating the input dataReading linesClosingSlide 13Text filesMy LineReader classBasics of the LineReader constructorThe full LineReader constructorreadLinecloseHow did I figure that out?The LineWriter classThe constructor for LineWriterFlushing the bufferPrintWriterwriteLineSlide 26Slide 27About JFileChoosersTypical JFileChooser windowJFileChooser constructorsUseful JFileChooser methods IUseful JFileChooser methods IIUsing a FileSlide 34SerializationConditions for serializabilityImplementing SerializableWriting objects to a fileReading objects from a fileWhat have I left out?The EndJan 14, 2019Simple Java I/OPart IGeneral Principles2Prologue“They say you can hold seven plus or minus two pieces of information in your mind. I can’t remember how to open files in Java. I’ve written chapters on it. I’ve done it a bunch of times, but it’s too many steps. And when I actually analyze it, I realize these are just silly design decisions that they made. Even if they insisted on using the Decorator pattern in java.io, they should have had a convenience constructor for opening files simply. Because we open files all the time, but nobody can remember how. It is too much information to hold in your mind.”—Bruce Eckel, http://www.artima.com/intv/aboutme2.html3StreamsAll modern I/O is stream-basedA stream is a connection to a source of data or to a destination for data (sometimes both)An input stream may be associated with the keyboardAn input stream or an output stream may be associated with a file Different streams have different characteristics:A file has a definite length, and therefore an endKeyboard input has no specific end4How to do I/O import java.io.*;Open the streamUse the stream (read, write, or both)Close the stream5Why Java I/O is hardJava I/O is very powerful, with an overwhelming number of optionsAny given kind of I/O is not particularly difficultThe trick is to find your way through the maze of possibilitiesopenuseclose6Opening a streamThere is data external to your program that you want to get, or you want to put data somewhere outside your programWhen you open a stream, you are making a connection to that external placeOnce the connection is made, you forget about the external place and just use the streamopenuseclose7Example of opening a streamA FileReader is a used to connect to a file that will be used for input: FileReader fileReader = new FileReader(fileName);The fileName specifies where the (external) file is to be foundYou never use fileName again; instead, you use fileReaderopenuseclose8Using a streamSome streams can be used only for input, others only for output, still others for bothUsing a stream means doing input from it or output to itBut it’s not usually that simple--you need to manipulate the data in some way as it comes in or goes outopenuseclose9Example of using a stream int charAsInt;charAsInt = fileReader.read( );The fileReader.read() method reads one character and returns it as an integer, or -1 if there are no more characters to readThe meaning of the integer depends on the file encoding (ASCII, Unicode, other)You can cast from int to char: char ch = (char)fileReader.read( );openuseclose10Manipulating the input dataReading characters as integers isn’t usually what you want to doA BufferedReader will convert integers to characters; it can also read whole linesThe constructor for BufferedReader takes a FileReader parameter: BufferedReader bufferedReader = new BufferedReader(fileReader);openuseclose11Reading lines String s;s = bufferedReader.readLine( );A BufferedReader will return null if there is nothing more to readopenuseclose12ClosingA stream is an expensive resourceThere is a limit on the number of streams that you can have open at one timeYou should not have more than one stream open on the same fileYou must close a stream before you can open it againAlways close your streams!Java will normally close your streams for you when your program ends, but it isn’t good style to depend on thisopenusecloseJan 14, 2019Simple Java I/OPart IILineReader and LineWriter14Text filesText (.txt) files are the simplest kind of filesText files can be used by many different programsFormatted text files (such as .doc files) also contain binary formatting informationOnly programs that “know the secret code” can make sense of formatted text filesCompilers, in general, work only with text15My LineReader classclass LineReader { BufferedReader bufferedReader; LineReader(String fileName) {...} String readLine( ) {...} void close( ) {...}}16Basics of the LineReader constructorCreate a FileReader for the named file: FileReader fileReader = new FileReader(fileName);Use it as input to a BufferedReader: BufferedReader bufferedReader = new BufferedReader(fileReader);Use the BufferedReader; but first, we need to catch possible Exceptions17The full LineReader constructor LineReader(String fileName) { FileReader fileReader = null; try { fileReader = new FileReader(fileName); } catch (FileNotFoundException e) { System.err.println ("LineReader can't find input file: " + fileName); e.printStackTrace( ); } bufferedReader = new BufferedReader(fileReader); }18readLineString readLine( ) { try { return bufferedReader.readLine( ); } catch(IOException e) { e.printStackTrace( ); } return null;}19closevoid close() { try { bufferedReader.close( ); } catch(IOException e) { }}20How did I figure that out?I wanted to read lines from a fileI thought there might be a suitable readSomething method, so I went to the API IndexNote: Capital letters are all alphabetized before lowercase in the IndexI found a readLine method in several classes; the most promising was the BufferedReader classThe constructor for BufferedReader takes a Reader as an argumentReader is an abstract class, but it has several implementations, including InputStreamReaderFileReader is a subclass of InputStreamReaderThere is a constructor for FileReader that takes as its argument a (String) file name21The LineWriter classclass LineWriter { PrintWriter printWriter; LineWriter(String fileName) {...} void writeLine(String line) {...} void close( )
View Full Document