java - i/o classesww2.cs.fsu.edu/~thrasher/cop3252/lectures/lec13.pdf · java.nio • in java 6,...
TRANSCRIPT
Summer 2019
I/O CLASSES
FILE CLASS
• File is a class used for retrieving properties of files or directories on a disk
• Objects of class File do not open files or provide file processing features
• There are a few constructors, including one that just takes a String representing the path to the file/directory
• Many of the methods in the File class are purely for gathering information. Examples:
• canExecute() – Does this application have execute permissions on the file?
• getAbsolutePath() – Returns the absolute pathname of the file as a String
• isFile() – Is this a normal file?
• isDirectory() – Is this a directory?
• exists() – Does this file/directory even exist?
• list() – Returns an array of Strings with the names of files contained in this directory
• listFiles() - Returns an array of Files with the names of files contained in this directory
FILE CLASS
• Other methods actually make changes that don’t require the file to be opened. Examples:
• delete() – deletes this file or directory
• deleteOnExit() – deletes this file or directory when the JVM exits
• mkdir() – creates a directory with the path of this File object
• setReadOnly() – sets permissions of this file/directory to read-only
STREAMS
• In Java, I/O is handled with streams
• A stream is a buffer of data flowing from one place to another
• An input stream flows from an input source (keyboard, file, etc.) into a program,
usually to be stored in variables
• An output stream flows from a program to an output destination (screen, file, etc.)
BUILT-IN STREAMS
• Three stream objects are already associated with devices in Java
• System.in – standard input stream object
• System.out – standard output stream object
• System.err – standard error stream object
• Many I/O libraries are in the package java.io
• You can see the hierarchy of java.io classes here
BUILT-IN STREAMS
• There are many built-in stream classes in Java for processing different types of data. Two
primary categories: byte streams and character streams
• InputStream is the base class for byte stream input classes
• OutputStream is the base class for byte stream output classes
• Reader is the base class for character stream input classes
• Writer is the base class for character stream output classes
• Byte streams read one byte at a time (binary data)
• Character streams read one character at a time (unformatted text)
STREAMS
• When using streams, note that there are often checked exceptions that need to be
handled. So pay attention to which methods can throw them.
• Example: Input streams will have various read() methods that may throw an IOException
• Also be aware that the various streams should be closed when you finish with them
• This is done using the close() method
• Streams are all considered resources, so you can use try with resources to close
them, as well (review the exception slides if you need to)
TYPES OF FILES
• Text File: A file made of readable text characters, looks like screen output
• Binary File: A binary file containing unformatted data saved in its raw memory format
• Text files are typically created with character-based streams, while binary files are
typically created with byte streams
• Sequential File: No regular record structure, typically read or written as an entire file
• Random Access File: Structured as uniformly-sized records. Can read/write either
sequentially or by accessing records anywhere in the file
FILE I/O
• Basic file I/O classes
• FileInputStream – for byte streams
• FileOutputStream – for byte streams
• FileReader – for character streams
• FileWriter – for character streams
• For the input streams, the primary method is called read. There is a version that reads
one byte (or char) and a version that reads an array of bytes (or chars)
• For output streams, the primary method is called write. Versions for single bytes/chars
and arrays of bytes/chars.
• JFileChooser – a Swing component for popping up a dialog box for easy browsing
and selection of a file (we will return to this later)
• Example: CopyFileUsingByteStream.java – older example which uses the file stream
classes to copy one file to another
BUFFERED STREAMS
• Buffered streams help increase efficiency. They use a buffered array of bytes or
characters. The buffered stream classes are:
• BufferedInputStream - for byte streams
• BufferedOutputStream - for byte streams
• BufferedReader - for character streams
• BufferedWriter - for character streams
• Buffered streams are used to add functionality to other streams (buffering)
• Usually constructed out of other stream objects
BUFFERED STREAMS
• For example, to apply buffered streams to file i/o, we can create file streams then wrap
them in a buffered stream object. Examples:
BufferedReader infile1 = new BufferedReader(
new FileReader(filename));
BufferedOutputStream outfile1 =
new BufferedOutputStream(
new FileOutputStream(filename));
Reader r1 = new BufferedReader(
new FileReader("file1.txt"));
JAVA.NIO
• In Java 6, Java’s “New I/O” APIs were introduced
• These are stored in the java.nio package
• We won’t go into detail on these
• The major difference in philosophy between this and the traditional java.io package is
that java.nio objects are meant for non-blocking I/O (note that this is generalization and
does not apply 100%)
• Blocking I/O stops all other processing when a thread invokes a read/write request. If
there is no data available, the thread stops until data is available.
• Non-blocking I/O can request some data for reading/writing, but if there is no data, it
continues processing other requests, often other I/O calls.
• So, the new I/O package is better for reading/writing from multiple places at once (this is
very useful when reading through network connections)
• This is often done using a Selector object
FILES
• One very useful class in the java.nio set of packages (even if you are working with the older I/O packages) is the Files class
• This class often interacts with other objects in the java.nio.file package, such as Path and Paths
• This class contains a number of static methods that are used for working with files
• Many of these do the same things that the File class does, but since the methods are static, you do not have to instantiate an object to do them
• Some examples (these assume that a path to a file is stored in the String strPath)://Returns true if the file at strPath exists
Files.exists(Paths.get(strPath));
//Returns true if the file at strPath is a directory
Files.isDirectory(Paths.get(strPath));
//Deletes the file found at strPath
Files.delete(Paths.get(strPath));
SOME EXAMPLES
• Test1.java - This program reads an input file and writes an all -uppercase copy of it to an
output file. First argument is the input file, second argument is the output file.
• Test1_2.java – This does the same as Test1.java, but does it using a custom version of a Writer
• Test2.java - This program reads an input file and counts the number of times a word
appears. First argument is the input file, second argument is the word to search for.
• Test3.java - This program uses some classes from the java.util package in addition
to a file reader, and it lists all the words in the input file along with the number of times
each word appears. The one command-line argument is the input file.
• Frost.txt - here is a sample text file you can use to test each of these programs
• Test4.java – This demonstrates using absolute paths and also uses java.nio
• Test5.java – Shows reading and writing to a random access file “at the same time”
QUALITY-OF-LIFE ADDITIONS
• Since Java 1.5, some new classes were introduced that made I/O tasks easier
• Formatter class – an interpreter for printf-style format strings. Can create a
Formatter object already attached to a file
• Scanner class – a text scanner that parses simple tokens more easily. Can create
a Scanner and pass in an input stream or a File object
I/O OF OBJECTS
• Serialization of objects: representing an object as a sequence of bytes that includes:
• The object’s data
• Information about the object’s type
• Information about the types of data in the object
• A serialized object can be written to a file as a single item and then read from a file and
deserialized
• This can be done with the classes:
• ObjectOutputStream
• ObjectInputStream
I/O OF OBJECTS
• An object can be serialized if its class implements the interface Serializable
• Serializable is a marker interface like Cloneable
• To write an object with class ObjectOutputStream, it must be a
Serializable object
• Each instance variable in the object must also be Serializable
• Or declared transient, which means it will be left out of the serialization
• Can combine with File I/O streams.
• Example:
ObjectOutputStream output;
Output = new ObjectOutputStream(
new FileOutputStream(“myfile.dat”));
I/O OF OBJECTS
• Actually reading and writing an entire object is done using the readObject() and
writeObject() methods of the appropriate object streams.
• When you are reading in an object using readObject(), it is always returned as type
Object, so you will almost always need to immediately cast it
• For example, let’s say you had a custom serializable class named Person, and an
ObjectOutputStream called output, to write the a Person object to a file, you would do
something like this:
Person p = new Person();
output.writeObject(p);
• If you wished to read a Person object from a file with an ObjectInputStream called
input, you would do this:
Person p = (Person) input.readObject();
SERIALIZATION EXAMPLE
• Foo.java – A serializable class example
• TestSerialize.java – Shows serialization of objects of type Foo
• TestDeserialize.java – Shows deserialization/reading of objects of type Foo
DEITEL EXAMPLES
• Some of these examples use newer features (Chapter 15 from current textbook)
• These are examples from an older edition of the textbook, some of which use Scanner
and Formatter
• These are examples from an even older edition that don’t use the new features