40
I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

Embed Size (px)

Citation preview

Page 1: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

I/O STREAMS

NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

Page 2: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

Reading Information into a Program – Input

Stream

Writing Information from a Program – Output

Stream

WHAT ARE I/O STREAMS?

Page 3: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

CopyBytes Read() and Write()

BYTE STREAMS

Page 4: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

• 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

CHARACTER STREAMS

Page 5: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

• 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

BUFFERED STREAMS

Page 6: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

• 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.

SCANNING AND FORMATTING

Page 7: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

• 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

I/O FROM THE COMMAND LINE

Page 8: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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

Page 9: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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

Page 10: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

JAVA FILE I/OWHAT 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.

Page 11: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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.

Page 12: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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)

Page 13: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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 withFiles.isReadable(path) Files.isWriteable(path) and Files.isExecutable(path)

whether two paths access the same file can be checked withFiles.isSameFile(path1, path2)

Page 14: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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

OUTLINE – RU WEN

Page 15: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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.

DELETING A FILE OR DIRECTORY

Page 16: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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.

o Example: import static java.nio.file.StandardCopyOption.*;

...

Files.copy(source, target, REPLACE_EXISTING);

COPYING A FILE OR DIRECTORY

Page 17: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

Method: move(Path, Path, CopyOption...)

o The 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.

o The following shows how to use the move method:

o example:

import static java.nio.file.StandardCopyOption.*;

...

Files.move(source, target, REPLACE_EXISTING);

MOVING A FILE OR DIRECTORY

Page 18: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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.

MANAGING METADATA (FILE AND FILE STORE ATTRIBUTES)-1

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.

Single attribute

Multiple attributes

Page 19: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

•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.

MANAGING METADATA (FILE AND FILE STORE ATTRIBUTES)-2

Page 20: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

The OpenOptions Parameters:

Write, append, truncate_existing, create_new, creat, delete_on_close, sparse, sync, dsync

READING, WRITING, AND CREATING FILES

File I/O Methods Arranged from Less Complex to More Complex

Page 21: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

READING, WRITING, AND CREATING FILES-2

Topics MethodsCommonly Used Methods for Small Files

readAllBytes(Path) or readAllLines(Path, Charset)

write(Path, byte[], OpenOption...), write(Path, Iterable< extends CharSequence>, Charset, OpenOption...)

Buffered I/O Methods for Text Files

newBufferedReader(Path, Charset)

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<?>)

Page 22: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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

RANDOM ACCESS FILES

Page 23: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

CREATING AND READING DIRECTORIES

Topics methodListing 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>)

Page 24: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

Part 4TOOL TALK W/ I/O STREAMS: FILE I/O

Read? Write?Where do I start?Ain’t no body got time for that?

Page 25: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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

T0PICS

Page 26: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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

SEEKABLE BYTE INTERFACE

Page 27: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

•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

READING AND WRITING

Page 28: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

SOURCE CODE: RANDOM ACCESS

Page 29: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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

CREATING/ READING DIRECTORIES

Page 30: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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

LINKS, SYMBOLIC OR OTHERWISE

Page 31: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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)

WHERE’S THE JAVA?

Page 32: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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

RECURSION IS BACK!! FILE I/O STYLE

Page 33: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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

Page 34: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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

FINDING FILES: JAVA STYLE

Page 35: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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? WHY BOTHER

Page 36: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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

DIRECTORY CHANGES

Page 37: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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

USEFUL METHODS

Page 38: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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 FILE I/O

Page 39: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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

LEGACY I/O FILE CODE

Page 40: I/O STREAMS NATHAN RAY, OSAMA MANSOUR, RU WEN, CARTER ADAMS

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

RESOURCES