Simple Java IO Part I General Principles Prologue

  • Slides: 41
Download presentation
Simple Java I/O Part I General Principles

Simple Java I/O Part I General Principles

Prologue “They say you can hold seven plus or minus two pieces of information

Prologue “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/aboutme 2. html 2

Streams n n n All modern I/O is stream-based A stream is a connection

Streams n n n All modern I/O is stream-based A 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 keyboard An input stream or an output stream may be associated with a file Different streams have different characteristics: n n A file has a definite length, and therefore an end Keyboard input has no specific end 3

How to do I/O import java. io. *; n n n Open the stream

How to do I/O import java. io. *; n n n Open the stream Use the stream (read, write, or both) Close the stream 4

Why Java I/O is hard n n n open use close Java I/O is

Why Java I/O is hard n n n open use close Java I/O is very powerful, with an overwhelming number of options Any given kind of I/O is not particularly difficult The trick is to find your way through the maze of possibilities 5

Opening a stream n n n open use close There is data external to

Opening a stream n n n open use close There is data external to your program that you want to get, or you want to put data somewhere outside your program When you open a stream, you are making a connection to that external place Once the connection is made, you forget about the external place and just use the stream 6

Example of opening a stream n open use close A File. Reader is a

Example of opening a stream n open use close A File. Reader is a used to connect to a file that will be used for input: File. Reader file. Reader = new File. Reader(file. Name); n n The file. Name specifies where the (external) file is to be found You never use file. Name again; instead, you use file. Reader 7

Using a stream n n n open use close Some streams can be used

Using a stream n n n open use close Some streams can be used only for input, others only for output, still others for both Using a stream means doing input from it or output to it But it’s not usually that simple--you need to manipulate the data in some way as it comes in or goes out 8

Example of using a stream open use close int ch; ch = file. Reader.

Example of using a stream open use close int ch; ch = file. Reader. read( ); n n The file. Reader. read() method reads one character and returns it as an integer, or -1 if there are no more characters to read The meaning of the integer depends on the file encoding (ASCII, Unicode, other) 9

Manipulating the input data n n n open use close Reading characters as integers

Manipulating the input data n n n open use close Reading characters as integers isn’t usually what you want to do A Buffered. Reader will convert integers to characters; it can also read whole lines The constructor for Buffered. Reader takes a File. Reader parameter: Buffered. Reader buffered. Reader = new Buffered. Reader(file. Reader); 10

Reading lines open use close String s; s = buffered. Reader. read. Line( );

Reading lines open use close String s; s = buffered. Reader. read. Line( ); n A Buffered. Reader will return null if there is nothing more to read 11

Closing n n n open use close A stream is an expensive resource There

Closing n n n open use close A stream is an expensive resource There is a limit on the number of streams that you can have open at one time You should not have more than one stream open on the same file You must close a stream before you can open it again Always close your streams! 12

Simple Java I/O Part II Line. Reader and Line. Writer

Simple Java I/O Part II Line. Reader and Line. Writer

Text files n Text (. txt) files are the simplest kind of files n

Text files n Text (. txt) files are the simplest kind of files n n text files can be used by many different programs Formatted text files (such as. doc files) also contain binary formatting information Only programs that “know the secret code” can make sense of formatted text files Compilers, in general, work only with text 14

My Line. Reader class Line. Reader { Buffered. Reader buffered. Reader; Line. Reader(String file.

My Line. Reader class Line. Reader { Buffered. Reader buffered. Reader; Line. Reader(String file. Name) {. . . } String read. Line( ) {. . . } void close( ) {. . . } } 15

Basics of the Line. Reader constructor n Create a File. Reader for the named

Basics of the Line. Reader constructor n Create a File. Reader for the named file: File. Reader file. Reader = new File. Reader(file. Name); n Use it as input to a Buffered. Reader: Buffered. Reader buffered. Reader = new Buffered. Reader(file. Reader); n Use the Buffered. Reader; but first, we need to catch possible Exceptions 16

The full Line. Reader constructor Line. Reader(String file. Name) { File. Reader file. Reader

The full Line. Reader constructor Line. Reader(String file. Name) { File. Reader file. Reader = null; try { file. Reader = new File. Reader(file. Name); } catch (File. Not. Found. Exception e) { System. err. println ("Line. Reader can't find input file: " + file. Name); e. print. Stack. Trace( ); } buffered. Reader = new Buffered. Reader(file. Reader); } 17

read. Line String read. Line( ) { try { return buffered. Reader. read. Line(

read. Line String read. Line( ) { try { return buffered. Reader. read. Line( ); } catch(IOException e) { e. print. Stack. Trace( ); } return null; } 18

close void close() { try { buffered. Reader. close( ); } catch(IOException e) {

close void close() { try { buffered. Reader. close( ); } catch(IOException e) { } } 19

How did I figure that out? n n I wanted to read lines from

How did I figure that out? n n I wanted to read lines from a file I thought there might be a suitable read. Something method, so I went to the API Index n n n Note: Capital letters are all alphabetized before lowercase in the Index I found a read. Line method in several classes; the most promising was the Buffered. Reader class The constructor for Buffered. Reader takes a Reader as an argument Reader is an abstract class, but it has several implementations, including Input. Stream. Reader File. Reader is a subclass of Input. Stream. Reader There is a constructor for File. Reader that takes as its argument a (String) file name 20

The Line. Writer class Line. Writer { Print. Writer print. Writer; Line. Writer(String file.

The Line. Writer class Line. Writer { Print. Writer print. Writer; Line. Writer(String file. Name) {. . . } void write. Line(String line) {. . . } void close( ) {. . . } } 21

The constructor for Line. Writer(String file. Name) { try { print. Writer = new

The constructor for Line. Writer(String file. Name) { try { print. Writer = new Print. Writer( new File. Output. Stream(file. Name), true); } catch(Exception e) { System. err. println("Line. Writer can't " + "use output file: " + file. Name); } } 22

Flushing the buffer n n When you put information into a buffered output stream,

Flushing the buffer n n When you put information into a buffered output stream, it goes into a buffer The buffer may not be written out right away If your program crashes, you may not know how far it got before it crashed Flushing the buffer is forcing the information to be written out 23

Print. Writer n n n Buffers are automatically flushed when the program ends normally

Print. Writer n n n Buffers are automatically flushed when the program ends normally Usually it is your responsibility to flush buffers if the program does not end normally Print. Writer can do the flushing for you public Print. Writer(Output. Stream out, boolean auto. Flush) 24

write. Line void write. Line(String line) { print. Writer. println(line); } 25

write. Line void write. Line(String line) { print. Writer. println(line); } 25

close void close( ) { print. Writer. flush( ); try { print. Writer. close(

close void close( ) { print. Writer. flush( ); try { print. Writer. close( ); } catch(Exception e) { } } 26

Simple Java I/O Part III JChoosers

Simple Java I/O Part III JChoosers

About JFile. Choosers n n n The JFile. Chooser class displays a window from

About JFile. Choosers n n n The JFile. Chooser class displays a window from which the user can select a file The dialog window is modal--the application cannot continue until it is closed Applets cannot use a JFile. Chooser, because applets cannot access files 28

Typical JFile. Chooser window 29

Typical JFile. Chooser window 29

JFile. Chooser constructors n JFile. Chooser() n n JFile. Chooser(File current. Directory) n n

JFile. Chooser constructors n JFile. Chooser() n n JFile. Chooser(File current. Directory) n n Creates a JFile. Chooser starting from the user’s directory Constructs a JFile. Chooser using the given File as the path JFile. Chooser(String current. Directory. Path) n Constructs a JFile. Chooser using the given path 30

Useful JFile. Chooser methods I n int show. Open. Dialog(Component enclosing. JFrame); n n

Useful JFile. Chooser methods I n int show. Open. Dialog(Component enclosing. JFrame); n n int show. Save. Dialog(Component enclosing. JFrame); n n Asks for a file to read; returns a flag (see below) Asks where to save a file; returns a flag (see below) Returned flag value may be: n n n JFile. Chooser. APPROVE_OPTION JFile. Chooser. CANCEL_OPTION JFile. Chooser. ERROR_OPTION 31

Useful JFile. Chooser methods II n File get. Selected. File() n n n show.

Useful JFile. Chooser methods II n File get. Selected. File() n n n show. Open. Dialog and show. Save. Dialog return a flag telling what happened, but don’t return the selected file After we return from one of these methods, we have to ask the JFile. Chooser what file was selected If we are saving a file, the File may not actually exist yet 32

Using a File n Assuming that we have successfully selected a File: n n

Using a File n Assuming that we have successfully selected a File: n n File file = chooser. get. Selected. File(); if (file != null) { String file. Name = file. get. Canonical. Path(); File. Reader file. Reader = new File. Reader(file. Name); Buffered. Reader reader = new Buffered. Reader(file. Reader); } File file = chooser. get. Selected. File(); if (file != null) { String file. Name = file. get. Canonical. Path(); File. Output. Stream stream = new File. Output. Stream(file. Name); writer = new Print. Writer(stream, true); } 33

Simple Java I/O Part IV Serialization

Simple Java I/O Part IV Serialization

Serialization n n You can also read and write objects to files Object I/O

Serialization n n You can also read and write objects to files Object I/O goes by the awkward name of serialization Serialization in other languages can be very difficult, because objects may contain references to other objects Java makes serialization (almost) easy 35

Conditions for serializability n If an object is to be serialized: n n The

Conditions for serializability n If an object is to be serialized: n n The class must be declared as public The class must implement Serializable The class must have a no-argument constructor All fields of the class must be serializable: either primitive types or serializable objects 36

Implementing Serializable n n To “implement” an interface means to define all the methods

Implementing Serializable n n To “implement” an interface means to define all the methods declared by that interface, but. . . The Serializable interface does not define any methods! n n Question: What possible use is there for an interface that does not declare any methods? Answer: Serializable is used as flag to tell Java it needs to do extra work with this class 37

Writing objects to a file Object. Output. Stream object. Out = new Object. Output.

Writing objects to a file Object. Output. Stream object. Out = new Object. Output. Stream( new Buffered. Output. Stream( new File. Output. Stream(file. Name))); object. Out. write. Object(serializable. Object); object. Out. close( ); 38

Reading objects from a file Object. Input. Stream object. In = new Object. Input.

Reading objects from a file Object. Input. Stream object. In = new Object. Input. Stream( new Buffered. Input. Stream( new File. Input. Stream(file. Name))); my. Object = (its. Type)object. In. read. Object( ); object. In. close( ); 39

What have I left out? n n n Encrypted files, compressed files, files sent

What have I left out? n n n Encrypted files, compressed files, files sent over internet connections, . . . Exceptions! All I/O involves Exceptions! try { statements involving I/O } catch (IOException e) { e. print. Stack. Trace ( ); } 40

The End 41

The End 41