1 / 40

I/O Streams

I/O Streams. Nathan Ray, osama mansour , Ru wen, carter adams. What are I/O Streams?. Writing Information from a Program – Output Stream. Reading Information into a Program – Input Stream. Byte Streams. Read() and Write(). CopyBytes. Character Streams.

arty
Download Presentation

I/O Streams

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. I/O Streams Nathan Ray, osamamansour, Ru wen, carter adams

  2. What are I/O Streams? Writing Information from a Program – Output Stream Reading Information into a Program – Input Stream

  3. Byte Streams Read() and Write() CopyBytes

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

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

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

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

  8. 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 Data Streams

  9. 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 Object Streams

  10. 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. Java File I/OWhat is a Path?

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

  12. 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) File operations

  13. 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) Checking a File or Directory

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

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

  16. Copying a File or Directory Method: copy(Path, Path, CopyOption...) • The copy fails if the target file exists, unless the REPLACE_EXISTING option is specified. • Directories can be copied. However, files inside the directory are not copied, so the new directory is empty even when the original directory contains files. • When 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. • Example: import static java.nio.file.StandardCopyOption.*; ... Files.copy(source, target, REPLACE_EXISTING);

  17. Moving a File or Directory Method:move(Path, Path, CopyOption...) • The move fails if the target file exists, unless the REPLACE_EXISTING option is specified. • Empty 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. • The following shows how to use the move method: • example: import static java.nio.file.StandardCopyOption.*; ... Files.move(source, target, REPLACE_EXISTING);

  18. Managing Metadata (File and File Store Attributes)-1 Single attribute Multiple attributes

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

  20. Reading, Writing, and Creating Files The OpenOptions Parameters: Write, append, truncate_existing, create_new, creat, delete_on_close, sparse, sync, dsync File I/O Methods Arranged from Less Complex to More Complex

  21. Reading, Writing, and Creating Files-2

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

  23. Creating and Reading Directories

  24. Read? Write? Where do I start? Ain’t no body got time for that? Tool Talk w/ I/O Streams: File I/O Part 4

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

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

  27. Reading and Writing • Difference between ByteChannel and SeekableByteChannel • 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

  28. Source Code: Random Access

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

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

  31. 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)

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

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

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

  35. 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)

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

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

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

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

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

More Related