Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


Share this Page URL
Help

Chapter 13: Input/Output > Random Access Files - Pg. 269

Random Access Files Using a stream to access a file dictates that the file is accessed sequentially, e.g. the first character must be read before the second, etc. Streams are ideal when the data comes in a sequential fashion, for example if the medium is a tape (widely used long ago before the emergence of harddisk) or a network socket. Streams are good for most of your applications, however sometimes you need to access a file randomly and using a stream would not be fast enough. For example, you may want to change the 1000 th byte of a file without having to read the first 999 bytes. For random access like this, there are a few Java types that offer a solution. The first is the java.io.RandomAccessFile class, which is easy to use but now out-dated. The second is the java.nio.channels.SeekableByteChannel interface, which should be used in new applications. A discussion of RandomAccessFile can be found in Chapter 13 of the previous edition of this book. This edition, however, teaches random access files using SeekableByteChannel. A SeekableByteChannel can perform both read and write operations. You can get an implementation of SeekableByteChannel using one of the Files class's newByteChannel methods: public static java.nio.channels.SeekableByteChannel newByteChannel(Path path, OpenOption... options) When using Files.newByteChannel() to open a file, you can choose an open option such as read-only or read-write or create-append. For instance Path path1 = ... SeekableByteChannel readOnlyByteChannel = Files.newByteChannel(path1, EnumSet.of(READ))); Path path2 = ... SeekableByteChannel writableByteChannel = Files.newByteChannel(path2, EnumSet.of(CREATE,APPEND)); SeekableByteChannel employs an internal pointer that points to the next byte to read or write. You can obtain the pointer position by calling the position method: