Java, What’s Old? Part III: I/O

Author: Anthony Goubard

Original post on Foojay: Read More

Table of Contents

ScannerMappedByteBufferRandomAccessFileLineNumberReaderConclusion

After Java, What’s Old? Part I: Collections and Java, What’s Old? Part II: Utils, let’s now have a look at less-known old input/output classes of the JDK that can still be useful.

Everything in this series will be in Java 8 and later, so after reading this article, you will be able to use it in your projects.

Scanner

Scanner is a class in java.util package that helps you parse files and input stream.

This class has support for regular expressions and Java data types.

Here are a few examples

  • new Scanner(file).useDelimiter("\p{Space}").nextInt();
    will get the first integer delimited by spaces
  • new Scanner(inputStream).useDelimiter("\A").next();
    will read the entire stream and return a String, as A pattern means beginning of the stream.
  • new Scanner(System.in).nextLine();
    will read the user input line on the console

MappedByteBuffer

MappedByteBuffer is part of java.nio package and is a ByteBuffer object whose content is a memory-mapped region of a file.

To create a new instance, use the FileChannel.map method.

It has different mode: read-only, read/write or private (also called copy-on-write)

This class was quite often used in the 1 Billion Row Challenge due to its efficiency.

Compared to a byte[], it has the advantages to have more methods such as nextLong(), asLongBuffer() or mismatch(ByteBuffer).

RandomAccessFile

A bit similar in term of functionality is the RandomAccessFile class.

This class exists since JDK 1.0 and allows to read or write any part of a local file.

This class has many methods to read and write data such as readLong(), readLine(), read(byte[]), writeUTF(String)

LineNumberReader

LineNumberReader is a not well know class that exists since JDK1.1.

This class is a BufferedReader that has the convenient getLineNumber() method. Like BufferedReader it also offers the useful readLine() method.

Scanner, RandomAccessFile and LineNumberReader are AutoCloseable classes, so don’t forget to call the close() method or put them in a try() block.

Conclusion

This is the last part of this “Java, What’s Old?” series. With part 1 and part 2, I hope some of you had the reaction “Hey, I didn’t know that! That might be useful.“. If so, don’t forget to share these articles online. And again, thank you to the Arnhem JUG for reviewing and letting me show this as presentation.

The post Java, What’s Old? Part III: I/O appeared first on foojay.