Download I/O Streams - UGA CS home page

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
I/O STREAMS
NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS
WHAT ARE I/O STREAMS?
Reading Infor mation into a
P r og r a m – I n p u t S t r e a m
Wr i t i n g I n f o r m a t i o n f r o m a
P r og r a m – O u t p u t S t r e a m
BYTE STREAMS
C o py B y t e s
R e a d ( ) a n d Wr i t e ( )
CHARACTER STREAMS
•
•
Same as CopyBytes code but uses FileReader and FileWriter for input and
output in place of FileInputStream and FileOutputStream
•
The returning int value holds a character value in its last 16 bits, whereas
CopyBytes holds and int variable byte value in its last 8 bits
Character streams are often "wrappers" for byte streams. The character stream
uses the byte stream to perform the physical I/O, while the character stream
handles translation between characters and bytes. FileReader, for example,
uses FileInputStream, while FileWriter uses FileOutputStream
•
Uses Line-Oriented I/O
BUFFERED STREAMS
• Buffered input streams read data from a memory area known as a buffer;
the native input API is called only when the buffer is empty. Similarly,
buffered output streams write data to a buffer, and the native output API is
called only when the buffer is full
• There are four buffered stream classes used to wrap unbuffered
streams: BufferedInputStream and BufferedOutputStream create buffered
byte streams, whileBufferedReader and BufferedWriter create buffered
character streams
• Flushing the buffer
SCANNING AND FORMATTING
• Programming I/O often involves translating to and from the neatly
formatted data humans like to work with. To assist you with these chores,
the Java platform provides two APIs. The scanner API breaks input into
individual tokens associated with bits of data. The formatting API
assembles data into nicely formatted, human-readable form.
I/O FROM THE COMMAND LINE
• The Java platform supports three Standard Streams: Standard Input,
accessed through System.in; Standard Output, accessed through System.out;
and Standard Error, accessed through System.err. These objects are defined
automatically and do not need to be opened. Standard Output and
Standard Error are both for output; having error output separately allows
the user to divert regular output to a file and still be able to read error
messages. For more information, refer to the documentation for your
command line interpreter
• Before a program can use the Console, it must attempt to retrieve the
Console object by invoking System.console(). If the Console object is
available, this method returns it. If System.console returns NULL, then
Console operations are not permitted, either because the OS doesn't
support them or because the program was launched in a noninteractive
environment
DATA STREAMS
Data Streams allow for read/write of binary files which store primitive data types (char, double, int, etc.)
as well as Strings.
Data streams implement either the DataInput or DataOutput interfaces, and the most widely-used
implementations are DataInputStream and DataOutputStream
methods are readInt, readDouble, readUTF etc. and writeInt, writeDouble, writeUTF etc.
The DataOutputStream constructor takes an OutputStream as its argument. e.g.
out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(“filename”)))
The DataInputStream constructor takes an InputStream as its argument. e.g.
in = new DataInputStream(new BufferedInputStream(new FileInputStream(“filename”)))
Data streams detect END OF FILE by catching an EOFException
OBJECT STREAMS
Inherit from DataStreams and can read / write all primitive data types supported by DataStreams
The Object Stream classes are ObjectInputStream and ObjectOutputStream. Which work similarly to
DataInputStream and DataOutputStream
.writeObject will write serializable information of any object to a binary output stream. If an object
contains references to other objects, those objects are then output
An individual object will only be written to a single output steam once
.readObject will reconstruct these nested object hierarchies
JAVA FILE I/O
WHAT IS A PATH?
On Windows there are multiple root nodes (C:\ or D:\ etc.) on Linux/Unix/OS X there is a single root node /
An Absolute Path defines an exact location in the hierarchy and always begins with a root node (e.g. C: \Windows\System or
/home/username/Downloads/myfile.zip)
A Relative Path must be combined with another path to access a file. joe/foo is a relative path, without more information joe/foo
does not identify a file.
A Symbolic Link is a file that serves as a reference to another file (in some operating systems this is known as an Alias)
By and large, operations on symbolic links are automatically directed to the target of the link and thus symbolic links are
transparent to applications.
However when a link is deleted or renamed, the link is altered and not the target file.
THE PATH CLASS
The Path class was introduced in Java SE 7 and is part of the java.nio.file package
Path provides a representation of a path in the file system. Path is not system
independent, a Path object from a Windows application and a Path object from a
Unix application will differ
A Path object can be created with the get method of the Paths (note plural) helper
class. e.g. Path p1 = Paths.get(“/tmp/foo”)
Path has a number of methods for traversing directories, splitting and combining
paths.
toString()
getFileName()
getName()
getNameCount()
subpath()
getParent()
getRoot()
etc.
FILE OPERATIONS
The Files object in the java.nio.file package has static methods for reading, writing, and manipulating files
and directories. Files methods work on instances of Path objects.
Most resources accessed by Files implements the java.io.Closeable interface wherein a close() method frees
system resources allocated by the object.
All Files methods throw IOException
Several Files methods perform operations atomically on some OSes
Files methods are aware of symbolic links
Files methods can use glob syntax to specify pattern-matching behavior
(glob syntax includes expressions such as *.txt)
CHECKING A FILE OR DIRECTORY
If you have a Path representing a file or directory how can you tell if the file exists, if it is readable, if it is
writeable, if it is executable etc?
existence / nonexistence can be checked with Files.exists(path) and Files.notExists(path)
accessibility of a file can be checked with
Files.isReadable(path) Files.isWriteable(path) and Files.isExecutable(path)
whether two paths access the same file can be checked with
Files.isSameFile(path1, path2)
OUTLINE – RU WEN
Deleting a File or Directory
Copying a File or Directory
Moving a File or Directory
Managing Metadata (File and File Store Attributes)
Reading, Writing, and Creating Files
Random Access Files
Creating and Reading Directories
DELETING A FILE OR DIRECTORY
With symbolic links, the link is deleted and not the target of the link. With
directories, the directory must be empty, or the deletion fails.
Two methods:
1.
delete(Path)
Deletes the file or throws an exception if the deletion fails.
2. deleteIfExists(Path)
Deletes a file if it exists. But if the file does not exist, no exception is thrown.
COPYING A FILE OR DIRECTORY
Method: copy(Path, Path, CopyOption...)
o The copy fails if the target file exists, unless the REPLACE_EXISTING option is specified.
oDirectories can be copied. However, files inside the directory are not copied, so the new directory is empty
even when the original directory contains files.
oWhen copying a symbolic link, the target of the link is copied. If you want to copy the link itself, and not the
contents of the link, specify either the NOFOLLOW_LINKS or REPLACE_EXISTING option.
oExample:
import static java.nio.file.StandardCopyOption.*;
...
Files.copy(source, target, REPLACE_EXISTING);
MOVING A FILE OR DIRECTORY
Method: move(Path, Path, CopyOption...)
oThe move fails if the target file exists, unless the REPLACE_EXISTING option is specified.
oEmpty directories can be moved. If the directory is not empty, the move is allowed when the directory can
be moved without moving the contents of that directory.
oThe following shows how to use the move method:
oexample:
import static java.nio.file.StandardCopyOption.*;
...
Files.move(source, target, REPLACE_EXISTING);
MANAGING METADATA (FILE AND FILE STORE
ATTRIBUTES)-1
Single attribute
Multiple attributes
Methods
Comment
size(Path)
Returns the size of the specified file in bytes.
isDirectory(Path, LinkOption)
Returns true if the specified Path locates a file that is a
directory.
isRegularFile(Path, LinkOption...)
Returns true if the specified Path locates a file that is a
regular file.
isSymbolicLink(Path)
Returns true if the specified Path locates a file that is a
symbolic link.
isHidden(Path)
Returns true if the specified Path locates a file that is
considered hidden by the file system.
getLastModifiedTime(Path, LinkOption...)
setLastModifiedTime(Path, FileTime)
Returns or sets the specified file's last modified time.
getOwner(Path, LinkOption...)
setOwner(Path, UserPrincipal)
Returns or sets the owner of the file.
getPosixFilePermissions(Path, LinkOption...)
setPosixFilePermissions(Path,
Set<PosixFilePermission>)
Returns or sets a file's POSIX file permissions.
getAttribute(Path, String, LinkOption...)
setAttribute(Path, String, Object, LinkOption...)
Returns or sets the value of a file attribute.
readAttributes(Path, String, LinkOption...)
Reads a file's attributes as a bulk operation. The String parameter identifies the
attributes to be read.
readAttributes(Path, Class<A>, LinkOption...)
Reads a file's attributes as a bulk operation. The Class<A> parameter is the type of
attributes requested and the method returns an object of that class.
MANAGING METADATA (FILE AND FILE STORE
ATTRIBUTES)-2
•Basic File Attributes
BasicFileAttributes class, e.g. Files.readAttributes
•Setting Time Stamps
The set of basic attributes includes three time stamps: creationTime, lastModifiedTime, and lastAccessTime.
•DOS File Attributes
DosFileAttributes class, setAttribute(Path, String, Object, LinkOption...)
•POSIX File Permissions (Portable Operating System Interface for UNIX)
PosixFileAttributes class,e.g., toString
•Setting a File or Group Owner
FileSystem.getUserPrincipalLookupService
•User-Defined File Attributes
Use UserDefinedAttributeView to create and track your own file attributes.
•File Store Attributes
FileStore class. e.g., getFileStore(Path) method fetches the file store for the specified file.
READING, WRITING, AND CREATING FILES
File I/O Methods Arranged from Less Complex to More Complex
The OpenOptions Parameters:
Write, append, truncate_existing, create_new, creat, delete_on_close, sparse,
sync, dsync
READING, WRITING, AND CREATING FILES-2
Topics
Methods
Commonly Used Methods for Small
Files
readAllBytes(Path) or readAllLines(Path, Charset)
Buffered I/O Methods for Text Files
newBufferedReader(Path, Charset)
write(Path, byte[], OpenOption...), write(Path, Iterable< extends CharSequence>, Charset,
OpenOption...)
newBufferedWriter(Path, Charset, OpenOption...)
Methods for Unbuffered Streams and
Interoperable with java.io APIs
newInputStream(Path, OpenOption...), newOutputStream(Path, OpenOption...)
Methods for Channels and ByteBuffers
newByteChannel(Path, OpenOption...), newByteChannel(Path, Set<? extends OpenOption>,
FileAttribute<?>...)
Methods for Creating Regular and
Temporary Files
createFile(Path, FileAttribute<?>)
createTempFile(Path, String, String, FileAttribute<?>), createTempFile(String, String,
FileAttribute<?>)
RANDOM ACCESS FILES
Methods to set or query the position:
position – Returns the channel's current position
position(long) – Sets the channel's position
read(ByteBuffer) – Reads bytes into the buffer from the channel
write(ByteBuffer) – Writes bytes from the buffer to the channel
truncate(long) – Truncates the file (or other entity) connected to the channel
CREATING AND READING DIRECTORIES
Topics
method
Listing a File System's Root Directories
FileSystem.getRootDirectories
Creating a Directory
createDirectory(Path, FileAttribute<?>)
Creating a Temporary Directory
createTempDirectory(Path, String, FileAttribute<?>...)
createTempDirectory(String, FileAttribute<?>...)
Listing a Directory's Contents
newDirectoryStream(Path)
Filtering a Directory Listing By Using
Globbing
Created the filter, then use newDirectoryStream(Path, String)
method
Writing Your Own Directory Filter
newDirectoryStream(Path, DirectoryStream.Filter<? super Path>)
Read? Write?
Where do I start?
Ain’t no body got time for
that?
TOOL TALK W/
PartI/O
4
I/O STREAMS: FILE
T0PICS
Random Access Files
Creating and Reading Directories
Links, Symbolic or Otherwise
Walking through Files
Finding Files
Monitor Directory for Changes
Other Useful Methods
Legacy File I/O
SEEKABLE BYTE INTERFACE
A byte channel that maintains a current position and allows the position to be
changed
Byte Channel -> Entity(File) -> Read/Write
Key is the Current Position can be modified hence a database
READING AND WRITING
•Difference between ByteChannel and Seekable ByteChannel
•SeekableByteChannel return a position
•Casting to FileChannel
•Mapping Regions of file into memory faster access
•Locking a region of the file
•Reading and writing from absolute location
SOURCE CODE: RANDOM ACCESS
CREATING/ READING
DIRECTORIES
Listing a File Root Directories
Create a Directory
Creating a Temporary Directory
List Contents of Directories
Filtering a Directory by Listing
Writing you Own Directory Filter
LINKS, SYMBOLIC OR OTHERWISE
Symbolic Links: is a special file that serves as a reference to another file
Hard Links: is an actual link from one file to another
WHERE’S THE JAVA?
Symbolic Links
In the Files library there is a create symbolic link method
Hard Links
In the Files library there is a create link method
Detecting Symbolic Links
In the Files library there isSymbolicLink(Boolean) Method
Target of Symbolic Links
In the Files library there is a readSymbolicLink(Link)
RECURSION IS BACK!! FILE I/O
STYLE
FileVisitor interface allows us to perform recursion on a files in a file tree
Reasons: Deleting files, Finding Files, etc
Traversal is peformed with walk through methods
Control the flow:
Skip Directories, Perform Action s, etc
FINDING FILES
You have used pattern matching, before if you have done any shell scripting
Bascially a special character will be inputted to create a pattern then files name
can be created against the pattern
FINDING FILES: JAVA STYLE
PathMatcher Interface
getPathMatch(String): uses a string
Recursion is Back? Again
Yes, pattern matching and recursion go hand in hand because you need to go through files
to find a file(Similar to Unix find utility)
Source Code is Online
DIRECTORY CHANGES? WHY
BOTHER
Used for Applications that need to be notified of file change event. (IDE,
editors, etc.)
Watch Service Interface
Register Method registers an object with Watch Service
StandardWatchEventKinds
Records actions of Files(Created, Deleted, Modified etc)
DIRECTORY CHANGES
Processing Events
The order of Events in an event processing loop
poll(),poll(long, TimeUnit), take etc
Retrieve the File Name
The order of Events in an event processing loop
poll(),poll(long, TimeUnit), take etc
USEFUL METHODS
Determine MIME method
MIME? Message included in files generally indicate the files original name
Default File System
getDefault() Method retrievers the default file system
Path String Separator
Like / or \ when specifiying file paths
getSeperator() : Seperator as a String
File System File Stores
File Systems have stores to hold files and directories
Use the getFileStores() to retrieve the files stores where a files is located
LEGACY FILE I/O
Before Java SE 7, Release java.io.File class was the mechanism used for file
I/O.
Short Commings
Missed Error Handling(Exceptions not thrown)
rename file method not consistent across platform
No symbolic link support
Note enough support on file security data
Meta data access was ineffient
File methods weren’t large enough in size
No reliable recursive code with circular symbolic links
LEGACY I/O FILE CODE
Takes those short coming and improves them with additional toPath method,
and rich features of Path class
Code for deleting files
You can’t take existing code and directly use the Legacy I/O code. You could
use the File.toPath() as suggested or you would have to rewrite your whole
code to use the new features.
Reason being the File I/O was completely revamped in the Java SE 7
RESOURCES
Oracle Site:
http://docs.oracle.com/javase/tutorial/essential/io/
All In-depth functionality explanations with source code examples that were explained here can be
found on the link above