Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for...

41
Chapter 12 File Input and Output
  • date post

    22-Dec-2015
  • Category

    Documents

  • view

    237
  • download

    0

Transcript of Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for...

Chapter 12

File Input and Output

Topics

• Stream Classes

• Files

• Text Input and Output

• JFileChooser for GUI programs

• Binary files

Files

• Program data that is stored in variables ceases to exist when the program terminates.

• Files provide a way of storing data after the program terminates.

• There are two basic ways to store data in files– text data is human readable, system independent

– binary data has the same format as it would in memory

File I/O

• Once a file is opened by associating a File object to it, we can access the data in the file.

• To read data from or write data to a file, we must create one of the Java stream objects and attach it to the file.

Streams

• A stream is a sequence of data items, usually 8-bit bytes.

• Java has two types of streams: an input stream and an output stream.

• An input stream has a source form which the data items come, and an output stream has a destination to which the data items are going.

FileStreams

• FileOutputStream and FileInputStream are two stream objects that facilitate file access.

• FileReader and FileWriter are used for input and output of text data

• FileOutputStream allows us to output a sequence of bytes; values of data type byte.

File Input and Output

• The action of saving, or writing, data to a file is called file output.

• The action of reading data from a file is called file input.

• To work with files, we need to make an association between an object in the program and a file on the disk.– When a valid association is established, we say a file is

opened. – A file must be opened before we can do any input and

output to the file.

Text Files

• Data stored as text is easy for humans to deal with.

• All data is converted to string data.

• A file whose contents are stored in ASCII format is called a text file.

• A text file is what you create with vi.

• Text data is what we get from the keyboard and send to the console.

I/O Classes

• Keyboard input and console output

Input Files

• Several ways to create a FileInputStream – Give the constructor the name of the file

FileInputStream fin

= new FileInputStream(“sample.data”);– Create the FileInputStream and then open it

FileInputStream fin = new FileInputStream();

fin.open( “sample.data”);

• From the FileInputStream, we can create an InputStreamReader and BufferedReader just as we did for System.in

Text Input

• To read data from a text file, we use the FileReader and BufferedReader objects. – We first associate a BufferedReader object to a file.

– Then we read data, using the readLine method of BufferedReader.

– Finally, we convert the String to a primitive data type as necessary.

• This is the same process we used for reading from the keyboard

FileReader Class

• We can use the FileReader class to reduce the number of steps needed to create a BufferedReaderFileReader fin

= new FileReader("file.dat");

BufferedReader in

= new BufferedReader( fin);

Text Output

• PrintWriter is an object we use to generate a textfile.

• PrintWriter supports only two output methods: – print– println (for print line)

• An argument to the methods may be any primitive data type.

• The methods convert the parameter to string and output this string value.

• These should look familiar - System.out is a PrintWriter

PrintWriter Objects

• The constructor of PrintWriter requires a Writer object as its argument.FileWriter = new

FileWriter( "test.dat");

PrintWriter out

= new PrintWriter( fout);

IOExceptions for File I/O

• The methods that link a file to a Stream or Reader or Writer will all throw an IOException if they fail.– For reading, failure means the file wasn't

found

– For writing, you would get an error if a write-protected file of the same name exists.

File Objects

• An alternate approach to what we've seen so far is to use the File class

• Create a File object and associate it with the file from which we wish to read.File inFile = new File(“sample.data”);

• Associate it with a FileStream of the appropriate kind.FileInputStream fin = new FileInputStream( inFile);

Testing for File Success

• We can check if a File object is associated correctly to an existing file by calling its exists method:if (inFile.exists()){

//inFile is associated correctly to

//an existing file

} else {

//inFile is not associated to any //existing file

}

Working With Directories

• A File object may also be associated to a directory.File directory =

new File (“C:/JavaPrograms/Ch12”);

String filename[] = directory.list();

for (int i=0; i<filename.length; i++){

System.out.println(filename[i]);

}

• To determine if a File object is associated to a file or directory, we call its boolean method isFile

Paths for Input Files

• The code on the previous slide assumes that the file is located in the current directory.

• Otherwise, we must specify the path and file name when we call the constructor:

File inFile = new File(“C:/JavaPrograms”,”xyz.data”);

• The formatting of the path name and file name is different for different operating systems.

JFileChooser Objects

• For GUI programs, there is a Component that allows you to browse for files.

• A javax.swing.JFileChooser object allows the user to select a file.

• The showOpenDialog method displays a JFileChooser with an Open button.JFileChooser chooser = new JFileChooser();...chooser.showOpenDialog(null);

• The showSaveDialog method displays a JFileChooser with a Save button.

JFileChooser Methodss

• The getSelectedFile method retrieves the desired file.

• The getName and getAbsolutePath methods retrieve the name and full path of a selected file.

File Filters

• A file filter may be used to remove unwanted files from the list.

• Define a subclass of the javax.swing.filechooser.FileFilter class and provide the accept and getDescription methods.public boolean accept(File file)public String getDescription( )

• The accept method returns true if the parameter file is a file to be included in the list.

• The getDescription method returns a text that will be displayed as one of the entries for the “Files of Type:” drop-down list.

FileFilter and JFileChooser Objects

• When the filter class is defined, we can assign it to a file chooser to restrict the listing to the desired directories and files.JFileChooser chooser

= new JFileChooser();

chooser.setFileFilter(new JavaFilter(());

int status

= chooser.showOpenDialog(null);

Low-Level I/O

• Sometimes, it is convenient to work directly with bytes.

• In this case, you just create a Stream and use the read method to read one or more bytes at a time.

• Similarly, you can use StreamReaders and StreamWriters to work with text one character at a time.

Byte I/O

• We will process the following byte array:byte[] byteArray = {10, 20, 30, 40, 50, 60, 70, 80};

• We create a File object:File outFile = new File (“sample1.data”);

• Associate a new FileOutputStream object to outFile:FileOutputStream outStream =

new FileOutputStream(outFile);

• Write the whole byte array at once to the file:outstream.write(byteArray);

• After the values are written to the file, we must close the stream:outStream.close();

• If the stream object is not closed, then data may get lost due to data caching.

Data Caching

• Data is saved in blocks of bytes to reduce the time it takes to save all of our data.

• The operation of saving data as a block is called data caching.

• To carry out data caching, part of memory is reserved as a data buffer or cache, which is used as a temporary holding place.

• Data are first written to a buffer. When the buffer becomes full, the data in the buffer are actually written to a file.

• If there are any remaining data in the buffer and the file is not closed, those data will be lost.

Byte Input

• To read data into a program, we reverse the steps in the output routine.

• First we create a FileInputStream object:File inFile = new File(“sample1.data”);FileInputStream inStream = new FileInputStream(inFile);

• Next declare and create byteArray:int filesize = (int) inFile.length();byte[] byteArray = new byte[filesize];

Byte Input

• We can use the length method of the File class to determine the size of the file.

• This allows us to create an array of bytes whose size is the size of the file.

• Finally, we read the data into an array of bytes using the read method of FileInputStreaminStream.read(byteArray);

Using other Types of Data

• We can output other types of data if we can type cast them into bytes.

• To read the data back, we use the read method.

• Depending on the data type we converted the data from, we may need to type cast back into the original data type.

Binary Files

• Text files are not the most efficient way to store data.

• Storing data in binary format (the format used in memory) takes less space.

• Binary files are useful for data that olnly needs to be read by another program.

Classes for Binary Files

DataOutputStreams

• Using DataOutputStream allows us to output Java primitive data type values.

• A DataOutputStream object will convert the primitive data type values into a sequence of bytes.

• The argument to the DataOutputStream constructor is a FileOutputStream object.

• A DataOutputStream object does not get connected to a file directly.

• The role of a DataOutputStream object is to provide high-level access to a file by handling the data type conversions.

DataInputStreams

• To read data back from the file, we reverse the operation.

• We use three objects: File, FileInputStream, and DataInputStream.

• Data must be read in the order in which it was written; otherwise, the results will be unpredictable.

Binary Output

• FileOutputStream and DataOutputStream objects produce a binary file in which the contents are stored in the format (binary format) in which they are stored in the main memory.

Object I/O

• We can also store objects just as we can store primitive data values.

• To write objects to a file, we use ObjectOutputStream.

• To read objects from a file, we use ObjectInputStream.

Object I/O

• In this example, we will write Person objects to a file.

• The first step is to modify the Person class definition to allow ObjectOutputStream and ObjectInputStream to perform object I/O.

Serializable Interface

• We modify the definition by adding the phrase implements Serializable to it.import java.io.*;

class Person implements Serializable {

//the rest is the same

}

• There are no methods for us to define in the implementation class.

Object Output

• To save objects to a file, we first create an ObjectOutputStream object:File outFile = new File(“objects.dat”);

FileOutputStream outFileStream = new FileOutputStream(outFile);

ObjectOutputStream outObjectStream =

new ObjectOutputStream(outFileStream);

Object Output

• To save a Person object, we executePerson person = new

Person(“Mr. Espresso”, 20, ‘M’);

outObjectStream.writeObject(person);

Object Output

• Different types of objects may be saved to a single file.

• We can also mix objects and primitive data type values in the same file.

• If a file contains objects from different classes, they must be read in the correct order and the matching type casting must be applied.

Object Input

• To read objects from a file, we use FileInputStream and ObjectInputStream.

• We use the method readObject to read an object.• Because we can store any types of objects to a

single file, we must type cast the object read from the file.

• The readObject method can throw a ClassNotFoundException (wrong type casting) in addition to an IOException. – Either exception may be caught or propagated.