The class RandomAccessFile provides supports for non-sequential, direct or random access to a disk file. RandomAccessFile is a two-way stream, supporting both input and output operations in the same stream. RandomAccessFile can be treated as a huge byte array.
You can use a file pointer of type long , similar to array index, to access individual byte or group of bytes in primitive types such as int and double. The file pointer is located at 0 when the file is opened. It advances automatically for every read and write operation by the number of bytes processed. In constructing a RandomAccessFile , you can use flags 'r' or 'rw' to indicate whether the file is "read-only" or "read-write" access, e.
Read and write records from a RandomAccessFile. A student file consists of student record of name String and id int. Scanner class, which greatly simplifies formatted text input from input source e. Scanner , as the name implied, is a simple text scanner which can parse the input text into primitive types and strings using regular expressions.
It first breaks the text input into tokens using a delimiter pattern, which is by default the white spaces blank, tab and newline. The tokens may then be converted into primitive values of different types using the various nextXxx methods nextInt , nextByte , nextShort , nextLong , nextFloat , nextDouble , nextBoolean , next for String , and nextLine for an input line.
You can also use the hasNextXxx methods to check for the availability of a desired input. The commonly-used constructors are as follows. You can construct a Scanner to parse a byte-based InputStream e. The most common usage of Scanner is to read primitive types and String form the keyboard System. The nextXxx methods throw InputMismatchException if the next token does not match the type to be parsed. You can easily modify the above program to read the inputs from a text file, instead of keyboard System.
You can use hasNext coupled with next to iterate through all the String tokens. You can also directly iterate through the primitive types via methods hasNextXxx and nextXxx. Xxx includes all primitive types byte , short , int , long , float , double and boolean , BigInteger, and BigNumber. Instead of the default white spaces as the delimiter, you can set the delimiter to a chosen regular expression via these methods:. Read " Regular Expression " for more details.
You can use the following methods to find the next occurrence of the specified pattern using regular expressions:. By default, Scanner uses the default charset to read the character from the input source.
You can ask Scanner to read text file which is encoded using a particular charset, by providing the charset name. PrintWriter for formatted-text printing. To write formatted-text to console System. Varargs was introduced in JDK 1. You can also use the System. Formatter 's " Format String Syntax " for details on format specifiers. Scanner for formatted text input. It also introduced java.
Formatter for formatted text output. A Formatter is an interpreter for printf -style format strings. It does not support String , probably because String is immutable.
Notice that the method format has the same syntax as the method printf , using the same set of format specifier as printf. Using a StringBuilder which implements Appendable as the output sink for the Formatter.
Setting the charset for Formatter 's output. The Formatter with StringBuilder as the output sink allows you to build up a formatted string progressively.
To produce a simple formatted String , you can simply use the static method String. This is handy in the toString method, which is required to return a String. A path string could be used to locate a file , a directory or a symbolic link. A symbolic link or symlink is a special file that references another file.
A path string is system dependent, e. Windows uses semi-colon ';' as path separator; while Unixes use colon ': Windows supports multiple roots, each maps to a drive e.
A path could be absolute beginning from the root or relative which is relative to the current working directory. Path instance specifies the location of a file, or a directory, or a symbolic link. To create a Path , use the static method get of the helper class java. The helper class Paths contains exclusively static methods for creating Path objects. As the directory-separator is system dependent, for writing portable and more flexible program, it is recommended to use an existing Path instance as an anchor to resolve the filename, e.
A Path can be broken down as root, level-0, level-1, The method getNameCount returns the levels. The method getName i returns the name of level-i. The class Files contains exclusively static methods for file, directory and symlink operations such as create, delete, read, write, copy, move, etc. You can use static boolean methods Files. A Path could be verified to exist, or not exist, or unknown e.
If the status is unknown, the exists and noExists returns false. You could also use static boolean methods Files. Many of these methods take an optional second argument of LinkOption , which is applicable for symlink only.
You can use static methods delete Path to delete a file or directory. Directory can be deleted only if it is empty. A boolean method deleteIfExists is also available. The methods return the target Path. The methods accepts an optional third argument of CopyOption. For small files, you can use static methods Files. You can use Files. The optional OpenOption includes: The following example write a small text file in "UTF-8" , and read the entire file back as bytes as well as characters.
For Reading, use Files. For Writing, use the Files. The InputStream and OutputStream returned are not buffered. Beside using the Files. You can use the default file attributes or optionally define the initial attributes of the file. You can use one of the Files. You can list the contents of a directory by using the Files. The returned DirectoryStream object implements Iterable.
You can iterate thru the entries with for-each loop. Those entries that resulted in false accept will be discarded. The following program uses an anonymous instance of an anonymous DirectoryStream. Filter sub-class to filter the DirectoryStream. The call-back method accept returns true for regular files, and discards the rest. Take note that this filtering criterion cannot be implemented in a glob-pattern. You can use static method Files. Instead of implementing FileVisitor interface, you could also extend from superclass SimpleFileVisitor , and override the selected methods.
There are two versions of walkFileTree. The first version take a starting directory and a FileVisitor , and transverse through all the levels, without following the symlinks. The second version takes 2 additional arguments: File and Directory Class java. File class maintains these system-dependent properties, for you to write programs that are portable: List Directory For a directory, you can use the following methods to list its contents: FilenameFilter declares one abstract method: Read from the opened input stream until "end-of-stream" encountered, or write to the opened output stream and optionally flush the buffered output.
Reading from an InputStream The abstract superclass InputStream declares an abstract method read to read one data-byte from the input source: Flushing the OutputStream In addition, the OutputStream provides a flush method to flush the remaining bytes from the output buffer. Copying a file byte-by-byte without Buffering.
For example, the above example can be re-written in a much neater manner as follow: Copying a file with a Programmer-Managed Buffer. Copying a file with Buffered Streams. To use DataInputStream for formatted input, you can chain up the input streams as follows: You can choose the character set in the InputStreamReader 's constructor: The commonly-used Charset names supported by Java are: Latin-1 " UTF-8 ": Little-endian little byte first " UTF ": PrintWriter The byte-based java.
Object serialization import java. To prevent certain fields from being serialized, mark them using the keyword transient. This could cut down the amount of data traffic. The writeObject method writes out the class of the object, the class signature, and values of non- static and non- transient fields. Warning Message "The serialization class does not declare a static final serialVersionUID field of type long" Advanced This warning message is triggered because your class such as java.
You have these options: Simply ignore this warning message. If a serializable class does not explicitly declare a serialVersionUID , then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class.
Externalizable Interface The Serializable has a sub-interface called Externalizable , which you could used if you want to customize the way a class is serialized. Externalizable declares two abstract methods: Delimiter Instead of the default white spaces as the delimiter, you can set the delimiter to a chosen regular expression via these methods: Customized token delimiter import java. Regexe Pattern Matching You can use the following methods to find the next occurrence of the specified pattern using regular expressions: LF [UTF-8] The optional width indicates the minimum number of characters to be output.
The optional precision restricts the number of characters or number of decimal places for float-point numbers. The mandatory conversion-type-character indicates how the argument should be formatted.
The uppercase conversion code e. The Formatter has the following constructors: The format method can be used to write formatted text output: Path A path string could be used to locate a file , a directory or a symbolic link. Paths To create a Path , use the static method get of the helper class java. For example, import java. Files The class Files contains exclusively static methods for file, directory and symlink operations such as create, delete, read, write, copy, move, etc.
Do not follow symlinks. For example, to get the size of a file in JDK 1. Use static method java. They were proposed for standardization by David Gray the astute reader now understands their name quite some years ago, but not accepted, because they had not been tried sufficiently to find conceptual problems with them.
They have since been implemented by quite a few modern Lisp implementations. However, they do indeed have some inadequacies, and each implementation has addressed these in different ways. The situation today is that it's difficult to even find out how to get started using Gray streams.
This is why standards are important. Here's a list of some classes which you might wish for your new stream class to inherit from:. Using Clozure CL, though, if you want buffering for better performance, which, unless you know of some reason you wouldn't, you do, you should instead inherit from the appropriate ccl:: Notice that -mixin suffix in the names of all the ccl:: You might consider making your own class like this. If you want to be able to create an instance of your class with the: This is especially useful if you want to create a class which performs some simple filtering operation, such as changing everything to uppercase or to a different character encoding.
If you do this, you will definitely need to specialize ccl:: Your method on ccl:: If you need to make your functionality generic across all the different types of stream, probably the best way to implement it is to make it a mixin, define classes with all the variants of input, output, io, character, and binary, which inherit both from your mixin and from the appropriate other class, then define a method on ccl:: Note that some of these classes are internal to the CCL package.
If you try to inherit from those ones without the ccl:: That just means you used the wrong symbol, so add the prefix. Here's a list of some generic functions which you might wish to specialize for your new stream class, and which ought to be documented at some point.
The following functions are standard parts of Common Lisp, but behave in special ways with regard to Gray streams. Specifically, open and with-open-file accept a new keyword argument,: